package com.moleq.mgpos.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import jp.co.casio.caios.framework.device.DeviceCommon;
import jp.co.casio.caios.framework.device.Drawer;
import android.R.integer;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.adapter.SaleListViewAdapter;
import com.moleq.base.MGposSender;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.SmartBeep;
import com.moleq.device.BasePinPad;
import com.moleq.device.BaseScale;
import com.moleq.device.BaseScanner;
import com.moleq.device.CasioDisplayScreen;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.IPinPad;
import com.moleq.device.PaxPinPad;
import com.moleq.device.PaxPinPadSetting;
import com.moleq.device.ScaleSetting;
import com.moleq.device.ScannerSetting;
import com.moleq.device.printer.CasioPrinter;
import com.moleq.device.printer.Printer;
import com.moleq.device.printer.PrinterBufferRowColection;
import com.moleq.device.printer.TV88MPrinter;
import com.moleq.dialog.CheckOutDialog;
import com.moleq.dialog.GlobalDiscountManualDialog;
import com.moleq.dialog.ItemCouponDialog;
import com.moleq.dialog.ItemDiscountDialog2;
import com.moleq.dialog.ItemDiscountManualDialog;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.PaymentDialog2;
import com.moleq.dialog.TareDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.enums.ItemType;
import com.moleq.enums.PaymentType;
import com.moleq.enums.TransactionStatus;
import com.moleq.enums.TransactionType;
import com.moleq.logic.DialogManager;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.PosPrinter;
import com.moleq.logic.ReceiptManager;
import com.moleq.logic.TransactionManager;
import com.moleq.logic.UPC;
import com.moleq.logic.SaleList.OnItemDisplayListener;
import com.moleq.mgpos.widget.DisplayScreen;
import com.moleq.mgpos.widget.FlipChartPanel;
import com.moleq.mgpos.widget.NumberPad;
import com.moleq.mgpos.widget.NumberPadButton;
import com.moleq.mgpos.widget.FlipChartPanel.OnTouchFlipChartListener;
import com.moleq.mgpos.widget.NumberPad.NumberPadListener;
import com.moleq.models.BottleSetting;
import com.moleq.models.Departmant;
import com.moleq.models.DvrSetting;
import com.moleq.models.FreeFuncRpt;
import com.moleq.models.FreeFunction;
import com.moleq.models.FunctionPanel;
import com.moleq.models.GlobalDiscountSetting;
import com.moleq.models.GlobalInfo;
import com.moleq.models.InventorySetting;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.PosLineCoupon;
import com.moleq.models.PosLineCvvWic;
import com.moleq.models.PosLineDiscnt;
import com.moleq.models.PosLineItem;
import com.moleq.models.PosLineTares;
import com.moleq.models.PosSetting;
import com.moleq.models.PosTrns;
import com.moleq.models.PriceSetting;
import com.moleq.models.PrinterSetting;
import com.moleq.models.Product;
import com.moleq.models.SaleListItem;
import com.moleq.models.SubDepartmant;
import com.moleq.models.TareSetting;
import com.moleq.models.TaxSetting;
import com.moleq.models.PosTender;
import com.moleq.models.VdrCoupon;
import com.moleq.mgpos.activities.R;
import com.moleq.service.DepartmantService;
import com.moleq.service.FreeFuncService;
import com.moleq.service.InventorySettingService;
import com.moleq.service.PriceService;
import com.moleq.service.ProductService;
import com.moleq.service.ServiceManager;
import com.moleq.service.SubDepartmantService;
import com.moleq.service.VdrCouponService;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;

public class SaleActivity extends MoleQBaseActivity implements OnItemDisplayListener {

	private int mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;

	public void showAppl(){
		
		switch (Integer.valueOf(mCurrentFunctionOption.getTp_appl_fl())) {
		case 0:
			ProcessFuncation(mCurrentFunctionOption.getTp_func_key(), mCurrentFunctionOption);
			break;
		case 1:
			mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
			mCurrentFunctionOption.isAppl = "0";
			 DialogManager.show(SaleActivity.this,DialogManager.USER_APPROVAL);
			break;
		case 2:
			if (!mTransMgr.needToApproval){
				mCurrentApproval = MoleQConstants.STATE_SUBTOTAL_APPROVAL;
				mTransMgr.needToApproval = true;
				ServiceManager.getInstance().mPosTrnsService.UpdateTrnAppr("1", TransactionManager.getInstance().TransactionNo);
			}
			ProcessFuncation(mCurrentFunctionOption.getTp_func_key(), mCurrentFunctionOption);
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onReturnValue(int what, Object obj) {
		switch (what) {

		case MoleQConstants.ACTIVE_FUNCTION:
			//
			FunctionPanel fp = (FunctionPanel) obj;
			if (fp != null) {
				mCurrentFunctionOption = fp;
				
				switch (mCurrentFunctionOption.getTp_func_key()) {
				case MoleQConstants.FUNCTION_CANCEL:
					GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_CANCEL;
					if (mTransMgr.status == TransactionStatus.STARTED) {
		
						if (mTransMgr.tenderList.size() > 0) {
							MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_cancel_trans_error));
							return;
						}
		
						MessageBox.show(this, getResources().getString(R.string.msg_cancel_trns), mFuncCancellistener, MessageDialog.MESSAGE_BOX_YES_NO);
					}
					break;
				case MoleQConstants.FUNCTION_NO_SALE:
					GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_NO_SALE;
					if (mTransMgr.status == TransactionStatus.CLOSED) {
						MessageBox.show(this, getResources().getString(R.string.msg_no_sale), mNoSalelistener, MessageDialog.MESSAGE_BOX_YES_NO);
					} else {
						MessageBox.show(this, getResources().getString(R.string.msg_no_sale_error));
					}
					break;
				case MoleQConstants.FUNCTION_SIGN_OUT:
					if (mTransMgr.status == TransactionStatus.CLOSED || mTransMgr.mSaleListItems.getItemCount() == 0) {
						
						MessageBox.show(this, getResources().getString(R.string.msg_sign_out), mSignOutlistener, MessageDialog.MESSAGE_BOX_YES_NO);
					}else{
						MessageBox.show(this, getResources().getString(R.string.msg_sign_out_error));
						return;
					}
					break;

				default:
					showAppl();
					break;
				}
//				switch (Integer.valueOf(fp.getTp_appl_fl())) {
//				case 0:
//					ProcessFuncation(fp.getTp_func_key(), obj);
//					break;
//				case 1:
//					mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
//					 DialogManager.show(SaleActivity.this,DialogManager.USER_APPROVAL);
//					break;
//				case 2:
//					if (!mTransMgr.needToApproval){
//						mCurrentApproval = MoleQConstants.STATE_SUBTOTAL_APPROVAL;
//						mTransMgr.needToApproval = true;
//						ServiceManager.getInstance().mPosTrnsService.UpdateTrnAppr("1", TransactionManager.getInstance().TransactionNo);
//					}
//					ProcessFuncation(fp.getTp_func_key(), obj);
//					break;
//				default:
//					break;
//				}



				// if (fp.isTp_appl_fl()) {
				// mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
				// DialogManager.show(SaleActivity.this,
				// DialogManager.USER_APPROVAL);
				// }else{
				// ProcessFuncation(fp.getTp_func_key(), obj);
				// }
			}
			break;
			
		case R.id.buttonItemDisntConfirm:
			
			int disnttype = mCurrentFunctionOption.getTp_parameter2();
			
			switch (mCurrentFunctionOption.getTp_func_key()) {
			case MoleQConstants.FUNCTION_GLOBAL_DISCOUNT:
				
				mTransMgr.mSaleListItems.addGlobalDiscount(Double.valueOf(obj.toString()));
				refreshDisplayContent();
				
				break;
			case MoleQConstants.FUNCTION_ITEM_DISOCUNT: 
					mTransMgr.mSaleListItems.addItemDiscount(Double.valueOf(obj.toString()), null,disnttype);
			
				break;
			default:
				break;
			}

			break;	
		case R.id.buttonItemCouponConfirm:

			String type = mCurrentFunctionOption.getTp_parameter1();

			mTransMgr.mSaleListItems.addItemCoupon(Double.valueOf(obj.toString()), type);

			break;
		case MoleQConstants.PRINT_RECEIPT:
			ProcessFuncation(MoleQConstants.PRINT_RECEIPT, null);
			break;

		case R.id.buttonSaleItemDelete:

			final int deletePosition = Integer.valueOf((String) obj);
			scrollToRow(deletePosition);
			SaleListItem item = mTransMgr.mSaleListItems.getItem(deletePosition);
			if(item.getItemType() == ItemType.PACKAGE_PRICE_FIX || 
					item.getItemType() == ItemType.LIMITED_QTY_PRICE_FIX || 
					item.getItemType() == ItemType.DISCOUNT_AMOUNT || 
					item.getItemType() == ItemType.DISCOUNT_PERECENT ||
					item.getItemType() == ItemType.DISCOUNT_LINK){
				int index = mTransMgr.mSaleListItems.findByParent(item.getParentId());
				SaleListItem item2 = mTransMgr.mSaleListItems.getItem(index);
				String[] Vdr = item2.getVdrCouponBarcode();
				for (int i = 0; i < Vdr.length; i++) {
					if(Vdr[i] != null && Vdr[i].length() > 0 && !Vdr[i].equals("Vdr Coupon") && !Vdr[i].equals("Mult Vdr Coupon") && !Vdr[i].equals("Add Value")){
						String msg = "Please remove the vendor coupon first.";
						MessageBox.show(this, msg, mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
						return;
					}
				}
			}else{
				String[] Vdr = item.getVdrCouponBarcode();
				for (int i = 0; i < Vdr.length; i++) {
					if(Vdr[i] != null && Vdr[i].length() > 0 && !Vdr[i].equals("Vdr Coupon") && !Vdr[i].equals("Mult Vdr Coupon") && !Vdr[i].equals("Add Value")){
						String msg = "Please remove the vendor coupon first.";
						MessageBox.show(this, msg, mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
						return;
					}
				}
			}
			
			OnClickMessageListener mOnItemDiscountCouponClickMessageListener = new OnClickMessageListener() {

				@Override
				public void onClickYes() {
					SaleListItem item = mTransMgr.mSaleListItems.getItem(deletePosition);
					mTransMgr.mSaleListItems.remove(deletePosition);
					mDeleteMode = false;
					mAdapter.setShowControl(mDeleteMode);
				}

				@Override
				public void onClickNo() {
				}

				@Override
				public void onClickOK() {
				}

			};
			
			OnClickMessageListener mOnClickVdrMessageListener = new OnClickMessageListener() {

				@Override
				public void onClickYes() {
					SaleListItem item = mTransMgr.mSaleListItems.getItem(deletePosition);
					deleteVdrCoupon(item);
//					mTransMgr.mSaleListItems.remove(deletePosition);
					mTransMgr.mSaleListItems.removeItem(deletePosition);
//					mPosSender.send("VOID "+item.getName() +"   "
//							+MoleQUtil.fixPriceForScreen(item.getPrice()));
					mDeleteMode = false;
					mAdapter.setShowControl(mDeleteMode);
				}

				@Override
				public void onClickNo() {
				}

				@Override
				public void onClickOK() {
				}

			};
			
			if (mTransMgr.mSaleListItems.canSingleDeleteItem(deletePosition)) {
				String msg = "Do you want to remove the ";
				if (mTransMgr.mSaleListItems.getItem(deletePosition).getItemType() == ItemType.ITEM_COUPON) {
					msg += "item coupon?";
				}else if(mTransMgr.mSaleListItems.getItem(deletePosition).getItemType() == ItemType.VDR_COUPON){
					msg = "Are you sure to remove the vendor coupon?";
				}else{
					msg += "item discount?";
				}
				if(mTransMgr.mSaleListItems.getItem(deletePosition).getItemType() == ItemType.VDR_COUPON){
					MessageBox.show(this, msg, mOnClickVdrMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
				}else{
					MessageBox.show(this, msg, mOnItemDiscountCouponClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
				}
				
				return;
			}

			if (mTransMgr.mSaleListItems.checkIsLastItem(deletePosition)) {
				
				mPosSender.sendRed("VOID");
				deleteVdrCoupon(mTransMgr.mSaleListItems.getItem(deletePosition));
				mTransMgr.mSaleListItems.removeItem(deletePosition);
				// setDeleteMode(false);
				mDeleteMode = false;
				mAdapter.setShowControl(mDeleteMode);
				
			} else {
				MessageBox.show(this, this.getResources().getString(R.string.msg_del_last_item));
			}
			break;
			
		case MoleQConstants.FUNCTION_OPEN_DEPARTMENT:
			// open department
			mSaleListitem = (SaleListItem)obj;
			if (mTransMgr.TransType == TransactionType.WIC && !mSaleListitem.isWic()){
				MessageBox.show(this, "WIC-eligible Foods Only.");
				return;
			}
			
			if (mTransMgr.TransType == TransactionType.CVV && !mSaleListitem.isCvv()){
				MessageBox.show(this, "CVV-eligible Foods Only.");
				return;
			}
			
			ProcessedAge();
			break;
			
		case R.id.buttonWicInfoConfirm:
			PosLineCvvWic mPosLineWic = (PosLineCvvWic)obj;
			if (mPosLineWic.getVw_amount() < mTransMgr.getAmountPayable()) {
				MessageBox.show(SaleActivity.this, "WIC balance can not lower than total.");
				return;
			}
			mTransMgr.TransType = TransactionType.WIC;
			mTransMgr.CVVWicPrice = mPosLineWic.getVw_amount();
			refreshDisplayContent();	
			ServiceManager.getInstance().mPosLineCvvWicService.updateOrInsert(mPosLineWic);
			if (mPosLineCvvWic != null) mPosLineCvvWic.isInvalidDate = false;
			break;
		case R.id.buttonCvvInfoConfirm:
			mTransMgr.TransType = TransactionType.CVV;
			PosLineCvvWic mPosLineCvv = (PosLineCvvWic)obj;
			mTransMgr.CVVWicPrice = mPosLineCvv.getVw_amount();
			refreshDisplayContent();	
			ServiceManager.getInstance().mPosLineCvvWicService.updateOrInsert(mPosLineCvv);
			if (mPosLineCvvWic != null) mPosLineCvvWic.isInvalidDate = false;
			break;
		case R.id.buttonCvvInfoClose:
		case R.id.buttonWicInfoClose:
			if (mPosLineCvvWic != null && mPosLineCvvWic.isInvalidDate) {
				ServiceManager.getInstance().mPosLineCvvWicService.DeleteByAll();
				mPosLineCvvWic = null;
				mTransMgr.TransType = TransactionType.SALE;
				mTransMgr.CVVWicPrice = 0;
				refreshDisplayContent();
			}
			break;
		}
	}
	
	public void deleteVdrCoupon(SaleListItem item){
//		3.
		String[] VdrCoupon = item.getVdrCouponBarcode();
		for (int i = 0; i < VdrCoupon.length; i++) {
			if(VdrCoupon[i] != null && !VdrCoupon[i].equals("")){
				VdrCoupon mVdrCoupon = ServiceManager.getInstance().mVdrCouponService.findVdrCouponById(item.getVdr_coupon_code_no());
				if (VdrCoupon[i].equals("Vdr Coupon")) {
					if (mVdrCoupon.getCv_more_fl().equals("1")) {
						List<String> link = item.getLinkVdrCouponItem();
//						for (int j = 0; j < link.size(); j++) {
						for (int j = link.size() - 1; j >= 0 ; j--) {
//							for (int j2 = 0; j2 < mTransMgr.mSaleListItems.getItemCount(); j2++) {
							for (int j2 = mTransMgr.mSaleListItems.getItemCount() - 1; j2 >= 0; j2--) {
								SaleListItem linkitem = mTransMgr.mSaleListItems.getItem(j2);
								if(linkitem.getId().equals(link.get(j))){
									String[] vdrCouponBarcode = linkitem.getVdrCouponBarcode();
									for (int k = 0; k < vdrCouponBarcode.length; k++) {
										if(vdrCouponBarcode[k].equals(item.getUpc())){
											vdrCouponBarcode[k] = "";
										}
									}
									mTransMgr.mSaleListItems.getItem(j2).setVdrCouponBarcode(vdrCouponBarcode);
								}
							}
						}
					}else{
						int min = mVdrCoupon.getCv_min_qty();
						List<String> link = item.getLinkVdrCouponItem();
						for (int j = link.size() - 1;j >= 0 ; j--) {
							for (int j2 = mTransMgr.mSaleListItems.getItemCount() - 1; j2 >= 0; j2--) {
								SaleListItem linkitem = mTransMgr.mSaleListItems.getItem(j2);
								if(linkitem.getId().equals(link.get(j))){
									String[] vdrCouponBarcode = linkitem.getVdrCouponBarcode();
									for (int k = 0; k < vdrCouponBarcode.length; k++) {
										if(vdrCouponBarcode[k] != null && vdrCouponBarcode[k].equals(item.getUpc())){
											if(min > 0){
												vdrCouponBarcode[k] = "";
												min--;
											}
										}
									}
									mTransMgr.mSaleListItems.getItem(j2).setVdrCouponBarcode(vdrCouponBarcode);
								}
							}
						}
					}
				}else if(VdrCoupon[i].equals("Mult Vdr Coupon") || VdrCoupon[i].equals("Add Value")){
					int index = mTransMgr.mSaleListItems.findByParent(item.getParentId());
					SaleListItem linkVdrCoupon = mTransMgr.mSaleListItems.getItem(index);
					deleteVdrCoupon(linkVdrCoupon);
				}
			}
		}
	}

	public void dispose() {
		// disable all scanner
		mDeviceManager.disposeScanner();

		// disabel scale
		mDeviceManager.disposeScale();
		
		//disabel printer
		mDeviceManager.disposePrinter();
		
		if (mDeviceManager.screen != null && mDeviceManager.screen.isConnected()) {
			mDeviceManager.screen.onDisconnect();
		}

		mDeviceManager.resetALLDevices();

		if (mFlipChartPanel != null)
			mFlipChartPanel.dispose();

		mTransMgr.mSaleListItems.unRegisterAll();
		
		if (mPosSender != null) {
			mPosSender.Request_ClearDisplay();
			mPosSender.stop();
		}
			
	}

	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);

		switch (viewId) {
		case MoleQConstants.PAYMENT_CHECK_OUT:
			
			ProcessFuncation(MoleQConstants.PAYMENT_CHECK_OUT, "");
			ProcessFuncation(MoleQConstants.OPEN_CASH_DRAWER, "");
			ProcessFuncation(MoleQConstants.PRINT_RECEIPT, "");
			break;

		case R.id.buttondateClose:

			if (mTransMgr.mLoadPendingItemMode) {
				mTransMgr.mLoadPendingItemMode = false;
				MessageBox.show(this, this.getResources().getString(R.string.msg_not_old_enough_2));
			}

			TransactionManager.getInstance().mSaleListItems.removeInvalidAgeItem(0);
			TransactionManager.getInstance().announceChanges();
			break;
		case R.id.buttondateConfirm:

			String age_time = parm;
			TransactionManager.getInstance().setBirthdayDate(MoleQUtil.fixDateTime(age_time));

			ServiceManager.getInstance().mPosTrnsService.UpdateBirthday(TransactionManager.getInstance().getBirthdayDate(), TransactionManager.getInstance().TransactionNo);

			int year = TransactionManager.getInstance().Age;
			if (mTransMgr.mLoadPendingItemMode && TransactionManager.getInstance().haveInvalidAgeItem(year)) {
				mTransMgr.mLoadPendingItemMode = false;
				MessageBox.show(this, this.getResources().getString(R.string.msg_not_old_enough_2));
				TransactionManager.getInstance().mSaleListItems.removeInvalidAgeItem(year);
				TransactionManager.getInstance().announceChanges();
				return;
			}

			ProcessedAge();

			break;

		case R.id.buttonAgeInfoConfirm:
			String age_time2 = parm;
			TransactionManager.getInstance().setBirthdayDate(MoleQUtil.fixDateTime(age_time2));

			ServiceManager.getInstance().mPosTrnsService.UpdateBirthday(TransactionManager.getInstance().getBirthdayDate(), TransactionManager.getInstance().TransactionNo);

			int year2 = TransactionManager.getInstance().Age;
			if (mTransMgr.mLoadPendingItemMode && TransactionManager.getInstance().haveInvalidAgeItem(year2)) {
				mTransMgr.mLoadPendingItemMode = false;
				MessageBox.show(this, this.getResources().getString(R.string.msg_not_old_enough_2));
				TransactionManager.getInstance().mSaleListItems.removeInvalidAgeItem(year2);
				TransactionManager.getInstance().announceChanges();
				return;
			}

			ProcessedAge();
			break;

		// case R.id.buttonFuncShift:
		// if (mTransMgr.mSaleListItems.getItemCount() == 0)
		// return;
		// DialogManager.show(this, DialogManager.SHIFT);
		// break;
		// case R.id.buttonShiftInfoConfirm:
		// mAdapter.notifyDataSetChanged();
		// break;
		case R.id.btn_dialog_ok:

			switch (mCurrentApproval) { 
			case MoleQConstants.STATE_FUNCTION_APPROVAL:
				
				if (parm.equals("true")) {
					if (mCurrentFunctionOption != null && mCurrentFunctionOption.getTp_appl_fl().equals("1")) {
						mCurrentFunctionOption.isAppl = "1";
						ProcessFuncation(mCurrentFunctionOption.getTp_func_key(), mCurrentFunctionOption);
					}
				} else {
					MessageBox.show(this, getResources().getString(R.string.msg_user_not_exist), mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				}
				
				break;

			case MoleQConstants.STATE_SUBTOTAL_APPROVAL:

				if (parm.equals("true")) {
					DialogManager.show(SaleActivity.this, DialogManager.PAYMENT_SELECT);
				} else {
					MessageBox.show(this, getResources().getString(R.string.msg_user_not_exist), mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
				}
				break;
			}
			break;
			
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
			return true;

		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	private Button btnExit;
	private Button btnSaleOpenDepItem;
	private Button btnFunction;
	private Button btnHotpick;
	private Button btnSubtotal;
	private TextView tvCashier, tvTotal, tvSubTotal, tvTax, tvDiscount, tvDiscount_num, tvtrnstype;
	// tvCoupon, tvCoupon_num, tvtrnstype;
	private ImageView ivProductPic;
	private DeviceManager mDeviceManager;
	private GlobalInfo mGlobalInfo;
	private PriceService mPriceService;
	private ProductService mProductService;
	private DeviceSettingService mSettingService;
	private DepartmantService mDepartmantService;
	private SubDepartmantService mSubDepartmantService;
	private InventorySettingService mInventorySettingService;
	private FreeFuncService mFreeFuncService;
	private NumberPad mNumberPad;
	private TextView tv_qty;
	private int currentQty = 1;
	private SaleListItem mSaleListitem;
	private TransactionManager mTransMgr;
	private MessageDialog mMessageDialog;
	private FlipChartPanel mFlipChartPanel;
	private LayoutInflater mInflater;
	private int screenWidth;
	private int screenHeight;
	private BottleSetting mBottleSetting;
	private List<TareSetting> mTareSetting = new ArrayList<TareSetting>();
	private List<TaxSetting> mlistTaxSetting;
	private List<PosLineTares> mPosLineTaresList = new ArrayList<PosLineTares>();
	private List<FreeFunction> mFreeFunctionList = new ArrayList<FreeFunction>();
	private static TareDialog mTareDialog;
	private PosTrns mPosTrns;
	//private boolean mLoadPendingItemMode = false;
	private PosLineItem mPosLineItem;
	private PosLineCvvWic mPosLineCvvWic;
	private SubDepartmant deptSetting;
	private TextView tv_tare, tv_tare_num, tv_shift;
	private boolean mDeleteMode = false;
	public boolean mRefundMode = false;
	private ListView mListView;
	private TextView tvLabelPrice;
	private TextView tvLabelSubtotal;
	private TextView tvLabelDiscount;
	private TextView tvLabelTax;
	private TextView tvLabelTotal;
	private Thread mLoadItemThread;
	private TextView tvsptrnstype;
	private SaleListViewAdapter mAdapter;
	// private int mSelectIndex = -1;
	private SaleListItemCreator creator;
	private FunctionPanel mCurrentFunctionOption = null;
	private PaymentDialog2 mPaymentDialog2 = null;
	private PaymentDialog2 mPaymentDialog3 = null;
	DvrSetting mDvrSetting = null;
	private static String PRINTER_IP = "";
	
	private OnTouchFlipChartListener mOnTouchFlipChartListener = new OnTouchFlipChartListener() {

		@Override
		public void onFlipChartItemClick(SaleListItem item) {

			UPC upc = new UPC(item.getUpc(), UPC.INPUT_BY_NONE, GlobalInfo.getInstance().isNormalize);
			if (item.getQty() > 1) {
				mNumberPad.setQty(item.getQty());
			}else{
				mNumberPad.setQty(1);
			}
			keySearchItem(upc);
			
			mFlipChartPanel.displayItem(mSaleListitem);
		}

	};

	private NumberPadListener mNumberPadListener = new NumberPadListener() {

		@Override
		public void onClick(NumberPadButton button) {
			String tmp = "";

			switch (button) {
			case ENTER:

				tmp = mNumberPad.getBuffer();

				if (tmp == null || tmp.equals(""))
					return;
				
				UPC upc = new UPC(tmp, UPC.INPUT_BY_MANUAL, GlobalInfo.getInstance().isNormalize);
				if (upc.IsVdrCoupon) {
					if(!mRefundMode && mTransMgr.TransType != TransactionType.RETURN){
						mTransMgr.mSaleListItems.addVdrCoupon(upc);
					}
				}else{
					keySearchItem(upc);
				}
					
				mNumberPad.reset();
				currentQty = 1;
				tv_qty.setText(String.valueOf(mNumberPad.getQty()));
				// }
				break;
			case MULTIPLY:
				currentQty = mNumberPad.getQty();
				tv_qty.setText(String.valueOf(mNumberPad.getQty()));
				break;
			default:
				//
				break;
			}
		}
	};

	private OnClickMessageListener mOnClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
		}

		@Override
		public void onClickNo() {

		}

		@Override
		public void onClickOK() {
			if (mMessageDialog != null && mMessageDialog.isShowing()) {
				mDeviceManager.enableAllScanner();
				mMessageDialog.dismiss();
			}

		}

	};

	private OnClickMessageListener mNoSalelistener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			
			if (mCurrentFunctionOption.getTp_appl_fl().equals("1") && !mCurrentFunctionOption.isAppl.equals("1")) {
				showAppl();
			}else{
				mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, 0);
				mTransMgr.NoSaleTransaction();
				
				Printer printer = DeviceManager.getInstance().ReceiptPrinter;
				PrinterBufferRowColection prinerBuffer = ReceiptManager.getNoSaleReceipt(GlobalInfo.getInstance().cashier, mTransMgr);
				mTransMgr.SaveEJ(prinerBuffer.toReceipt());
				mPosSender.sendRed(MoleQUtil.getSenderString("COMPLETE NO SALE"));
				
				printer.open();
				if(printer.isEnable() && !printer.isBusy() && !printer.ismOutOfPaper()){
					printer.setPrinterBuffer(prinerBuffer);
					printer.print();
					printer.cutPaper();
				}
				printer.close();
				
				mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
				mTransMgr.CompleteTransaction();
				mTransMgr.Reset();
				mRefundMode = false; // cancel refund
				
				// ProcessFuncClick(FunctionOption.OPEN_CASH_DRAWER);
				ProcessFuncation(MoleQConstants.OPEN_CASH_DRAWER, "");
			}
		}

		@Override
		public void onClickNo() {
			// ProcessFuncClick(FunctionOption.NULL);
		}

		@Override
		public void onClickOK() {

		}

	};
	private OnClickMessageListener mNoPosSettingListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {

		}

		@Override
		public void onClickNo() {

		}

		@Override
		public void onClickOK() {
			finish();

		}

	};
	private OnClickMessageListener mFuncCancellistener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {

			if (mCurrentFunctionOption.getTp_appl_fl().equals("1") && !mCurrentFunctionOption.isAppl.equals("1")) {
				showAppl();
			}else{
				mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, mTransMgr.getSubTotal());
				mTransMgr.CancelTransaction();
	
				
				mPosSender.sendRed(MoleQUtil.getSenderString("COMPLETE CANCEL"));
				mPosSender.sendRed(MoleQUtil.getSenderString("END"));					
				Printer printer = DeviceManager.getInstance().ReceiptPrinter;
				PrinterBufferRowColection printBuffer = ReceiptManager.getCancelTrnReceipt(GlobalInfo.getInstance().cashier, mTransMgr);
				printer.open();
				if (printer.isEnable() && !printer.isBusy() && !printer.ismOutOfPaper()) {
					printer.setPrinterBuffer(printBuffer);
					printer.print();
					printer.cutPaper();
				}
				printer.close();
				mTransMgr.SaveEJ(printBuffer.toReceipt());
				mRefundMode = false; // cancel refund
				mDeleteMode = false;
				mAdapter.setShowControl(mDeleteMode);
				mTransMgr.Reset();
				mTransMgr.announceChanges();
				refreshDisplayContent();
			}
		}

		@Override
		public void onClickNo() {
		}

		@Override
		public void onClickOK() {

		}
	};
	
	private OnClickMessageListener mSignOutlistener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {

			if (mCurrentFunctionOption.getTp_appl_fl().equals("1") && !mCurrentFunctionOption.isAppl.equals("1")) {
				showAppl();
			}else{
				mTransMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_SIGN_OUT, 1, 0);
				mPosSender.sendRed(MoleQUtil.getSenderString("SIGN OUT"));
				
				mTransMgr.TransType = TransactionType.SALE;
				mTransMgr.Reset();
				dispose();
				finish();
			}

			// ProcessFuncClick(FunctionOption.OPEN_CASH_DRAWER);
		}

		@Override
		public void onClickNo() {
			// ProcessFuncClick(FunctionOption.NULL);
		}

		@Override
		public void onClickOK() {

		}

	};
	
	
	private MGposSender mPosSender;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);// Hidden title
		// Full Screen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_sale);

		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mTransMgr = TransactionManager.getInstance();
		mGlobalInfo = GlobalInfo.getInstance();
		mDeviceManager = DeviceManager.getInstance();
		mDeviceManager.resetALLDevices();

		DialogManager.buildDialogs(this);

		// init all component
		InitializeComponent();

		// setup servcice
		mProductService = ServiceManager.getInstance().mProductService;
		mPriceService = ServiceManager.getInstance().mPriceService;
		mSubDepartmantService = ServiceManager.getInstance().mSubDepartmantService;
		mDepartmantService = ServiceManager.getInstance().mDepartmantService;
		mSettingService = ServiceManager.getInstance().mDeviceSettingService;
		mFreeFuncService = ServiceManager.getInstance().mFreeFuncService;
		mInventorySettingService = ServiceManager.getInstance().mInventorySettingService;
		
		long iRow = 0;

		iRow = ServiceManager.getInstance().mPosSettingService.getRowCount();
		if (iRow == 0) {
			MessageBox.show(this, String.format(getResources().getString(R.string.msg_no_postting), "(POS Setting)"), mNoPosSettingListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}

		iRow = ServiceManager.getInstance().mGroupSettingService.getRowCount();
		if (iRow == 0) {
			MessageBox.show(this, String.format(getResources().getString(R.string.msg_no_postting), "(Group Setting)"), mNoPosSettingListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}

		iRow = ServiceManager.getInstance().mSubDepartmantService.getRowCount();
		if (iRow == 0) {
			MessageBox.show(this, String.format(getResources().getString(R.string.msg_no_postting), "(Sub Dept Setting)"), mNoPosSettingListener, MessageDialog.MESSAGE_BOX_OK);
			return;
		}

		// load all setting
		PosSetting mPosSetting = ServiceManager.getInstance().mPosSettingService.Find();
		mDvrSetting = ServiceManager.getInstance().mDvrSettingService.FindData();
		if (mPosSetting != null) {
			mGlobalInfo.storeNo = mPosSetting.getStore_no();
			mGlobalInfo.stationNo = mPosSetting.getPs_station();
			mGlobalInfo.openTime = mPosSetting.getPs_open_time();
			mGlobalInfo.closeTime = mPosSetting.getPs_close_time();
			mGlobalInfo.CurrencySign = mPosSetting.getCurrency_sign();
			mGlobalInfo.flipChartMax = mPosSetting.getPs_fc_max();
			mGlobalInfo.tareRate = mPosSetting.getPs_tare_rate();
			String weightUnit = mPosSetting.getPs_weight_unit();
			mGlobalInfo.weightUnit = weightUnit;
			mGlobalInfo.decimalPoint = MoleQUtil.getDecimalPoint(weightUnit);
			mGlobalInfo.priceDigits = mPosSetting.getPrice_digits();
			mGlobalInfo.isCalcWeight = mPosSetting.isCalcWeight();
			mGlobalInfo.outOfPaper = mPosSetting.isOutOfPaper();
			mGlobalInfo.calendar_type = mPosSetting.isCalendarType();
			mGlobalInfo.isNormalize = mPosSetting.isNormUpce();
			mGlobalInfo.isShowDesc = mPosSetting.isShowDesc();
//			mGlobalInfo.isUserDVR = mPosSetting.isDVR();
			mGlobalInfo.isZeroBaln = mPosSetting.isZeroBaln();
			mGlobalInfo.isZeroPrice = mPosSetting.isZeroPrice();
			mGlobalInfo.foodStampRule = mPosSetting.getPs_fs_tax_rule();
			mGlobalInfo.isPrintServiceItem = mPosSetting.isPrintServic();
			mGlobalInfo.isSigHost = mPosSetting.isSigHost();
			mGlobalInfo.isSaveSig = mPosSetting.isSaveSig();
			mGlobalInfo.sigMinValue = mPosSetting.getPs_sig_min();
			int roundId = mPosSetting.getPs_rounding();
			mGlobalInfo.mRoundingSetting = ServiceManager.getInstance().mRoundingSettingService.FindByID(roundId);
			mGlobalInfo.receiptPrinter = mPosSetting.getPs_receipt_pnt();
		}
		InventorySetting mInventorySetting = mInventorySettingService.FindData();
		if(mInventorySetting != null){
			if(mInventorySetting.getIs_onoff().equals("0")){
				GlobalInfo.getInstance().isInventory = false;
			}else{
				GlobalInfo.getInstance().isInventory = true;
			}
		}

		InitializeHardware();

		mlistTaxSetting = ServiceManager.getInstance().mTaxSettingService.FindAll();
		mTransMgr.setTaxSetting(mlistTaxSetting);

		mTransMgr.mSaleListItems.register(mFlipChartPanel);
		// mTransMgr.mSaleListItems.register(mSaleListView);
		mTransMgr.mSaleListItems.register(this);
		
		mPosSender = MGposSender.getInstance();
		if(mDvrSetting != null) {
			if (mDvrSetting.getDs_onoff().equals("1")) {
				mPosSender.setIpAddress(mDvrSetting.getDs_dvr_ip(), mDvrSetting.getDs_port());
				mPosSender.start();
			}
		}
		
		this.StartTransaction();

		creator = new SaleListItemCreator(this);
	}

	private void InitializeHardware() {
		List<ScannerSetting> scannerSettings = mSettingService.getScannerSettings();

		// check scanner
		int iScannerCount = scannerSettings.size();
		if (iScannerCount > 0) {
			for (int i = 0; i < iScannerCount; i++) {
				int iPort = scannerSettings.get(i).getPort();
				for (int j = i + 1; j < iScannerCount; j++) {
					if (iPort == scannerSettings.get(j).getPort()) {
						Toast.makeText(SaleActivity.this, " Scanner setup error. Please check.", Toast.LENGTH_LONG).show();

						finish();
					}

				}
			}

			// setup scanner
			for (int i = 0; i < scannerSettings.size(); i++) {
				BaseScanner baseScanner = new BaseScanner();
				baseScanner.setScannerSetting(scannerSettings.get(i));
				mDeviceManager.addScanner(baseScanner);
			}

			// open scanner
			for (int i = 0; i < mDeviceManager.scanners.size(); i++) {
				mDeviceManager.scanners.get(i).onConnect();
				mDeviceManager.scanners.get(i).setCallbackEvent(this);
				mDeviceManager.scanners.get(i).onEnableScanner();
			}

		}

		// check scale
		List<ScaleSetting> scaleSettings = mSettingService.getScaleSettings();
		if (scaleSettings.size() > 1) {
			Toast.makeText(SaleActivity.this, " Scale setup error. Please check.", Toast.LENGTH_LONG).show();

			finish();
		} else if (scaleSettings.size() == 1) {
			BaseScale scale = new BaseScale();
			scale.setScaleSetting(scaleSettings.get(0));
			mDeviceManager.setScale(scale);
			mDeviceManager.scale.onConnect();
			mDeviceManager.scale.setCallbackEvent(this);
		}

		CasioDisplayScreen displayer = new CasioDisplayScreen();
		// setup screen
		mDeviceManager.setScreen(displayer);
		mDeviceManager.screen.onConnect();

		// setup printer
		// mDeviceManager.setPrinter(new CasioPrinter());
//		mDeviceManager.setPrinter(new PosPrinter());
//		mDeviceManager.printer.onConnect();
//		mDeviceManager.printer.setEnable(!mGlobalInfo.outOfPaper);
		
		List<PrinterSetting> listPrinter = ServiceManager.getInstance().mPrinterSettingService.FindAll();
		DeviceManager.getInstance().ServiceTicketPrinters = new HashMap<Integer, Printer>();
		for (int i = 0; i < listPrinter.size(); i++) {
			TV88MPrinter epson = new TV88MPrinter();
			epson.setIpAddress(listPrinter.get(i).getPs_ip(), listPrinter.get(i).getPs_port());
			DeviceManager.getInstance().ServiceTicketPrinters.put(listPrinter.get(i).getPs_id(), epson);
		}
		
		CasioPrinter casioPtr = new CasioPrinter();
		DeviceManager.getInstance().ServiceTicketPrinters.put(0, casioPtr);
		
		mDeviceManager.ReceiptPrinter = DeviceManager.getInstance().ServiceTicketPrinters.get(mGlobalInfo.receiptPrinter);
		mDeviceManager.ReceiptPrinter.setmOutOfPaper(mGlobalInfo.outOfPaper);
		
		// setup pos device
		PaxPinPadSetting posDevSetting = new PaxPinPadSetting();
		posDevSetting = ServiceManager.getInstance().mPinPadService.getPinPadSetting();
		if (posDevSetting == null)
			mDeviceManager.pinPadIsReady = false;
		else
			mDeviceManager.pinPadIsReady = true;
		if (mDeviceManager.pinPadIsReady) {
			BasePinPad posdev = new PaxPinPad(GlobalInfo.getInstance().appDataFolder);
			posdev.setPinPadSetting(posDevSetting);
			posdev.isUploadSignatureCapture = mGlobalInfo.isSigHost;
			
			mDeviceManager.setPinPad(posdev);
			mDeviceManager.pinPad.onConnect();
			mDeviceManager.pinPad.initialize();
		}

	}

	private OnClickListener OnClickControlListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.buttonSaleExit:
				mTransMgr.TransType = TransactionType.SALE;
				mTransMgr.Reset();
				dispose();
				finish();
				break;
			case R.id.buttonSaleOpenDepartment:
				DialogManager.show(SaleActivity.this, DialogManager.OPEN_DEPTMENT);
				break;

			case R.id.buttonSaleFunction:
				DialogManager.show(SaleActivity.this, DialogManager.FUNCTION_SELECTION);
				break;

			case R.id.buttonSaleHotpick:
				if (mFlipChartPanel == null || mFlipChartPanel.isShowing())
					return;
				mFlipChartPanel.show();
				break;
			case R.id.buttonSaleSubtotal:
				if (mTransMgr.mSaleListItems.getItemCount() == 0) {
					MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_no_item));
					return;
				}

				// mTransMgr.tr
				if (mTransMgr.getAmountPayable() >= 0) {
					
					if (!mGlobalInfo.isZeroBaln && mTransMgr.getAmountPayable() == 0) {
						return;
					}
					
					if (mTransMgr.needToApproval) {
						mCurrentApproval = MoleQConstants.STATE_SUBTOTAL_APPROVAL;
						DialogManager.show(SaleActivity.this, DialogManager.USER_APPROVAL);
					} else {
						PosTender mPosTender = new PosTender();
						if (mTransMgr.TransType == TransactionType.WIC) {
							mPosTender.setPt_seq_no(mTransMgr.tenderList.size() + 1);
							mPosTender.paymentType = PaymentType.WIC;
							mPosTender.setPt_tender(mTransMgr.getAmountPayable());
							mPosTender.setPt_trn_no(mTransMgr.TransactionNo);

							mPaymentDialog2 = new PaymentDialog2(SaleActivity.this,R.style.dialog);
							mPaymentDialog2.show();
							mPaymentDialog2.mCurrentTender = mPosTender;
							mPaymentDialog2.ConfirmTender();
							mPaymentDialog2.checkout();
							
							
							
						}else if(mTransMgr.TransType == TransactionType.CVV){
							
							
							
							if (mPaymentDialog3 == null || !mPaymentDialog3.isShowing())
							{
								mPaymentDialog3 = new PaymentDialog2(SaleActivity.this,R.style.dialog);
							}
							
							if (mPaymentDialog3.isShowing()) {
								return;
							}
							
							int cvvidx = mTransMgr.getCvvTender();
							if (cvvidx >= 0 ) {
								double price = mTransMgr.CVVWicPrice - mTransMgr.getAmountPayable()> 0?mTransMgr.getAmountPayable():mTransMgr.CVVWicPrice;
								mTransMgr.tenderList.get(cvvidx).setPt_tender(price);
								mPaymentDialog3.mCurrentTender.paymentType = PaymentType.CVV;
								mPaymentDialog3.mCurrentTender.setPt_tender(price);
							}else{
								mPosTender.setPt_seq_no(mTransMgr.tenderList.size() + 1);
								mPosTender.paymentType = PaymentType.CVV;
								mPosTender.setPt_tender(mTransMgr.CVVWicPrice - mTransMgr.getAmountPayable()> 0?mTransMgr.getAmountPayable():mTransMgr.CVVWicPrice);
								mPosTender.setPt_trn_no(mTransMgr.TransactionNo);
								mPaymentDialog3.mCurrentTender = mPosTender;
								
							}
							
							mPaymentDialog3.show();
							mPaymentDialog3.ConfirmTender();
							mPaymentDialog3.checkout();
							
						}else{
							mDeleteMode = false;
							mAdapter.setShowControl(mDeleteMode);
							DialogManager.show(SaleActivity.this, DialogManager.PAYMENT_SELECT);
						}
					}
					
					
				}
				
				break;
			}

		}
	};
	
	public boolean isApproval() {
		int re = 0;
		mFreeFunctionList = mFreeFuncService.getActiveFreeFunction();
		for (int i = 0; i < GlobalInfo.getInstance().useFuntionsList.size(); i++) {
			for (int j = 0; j < mFreeFunctionList.size(); j++) {
				if (GlobalInfo.getInstance().useFuntionsList.get(i) == mFreeFunctionList.get(j).getFf_id()) {
					re++;
				}
			}
		}
		if (re > 0) {
			return true;
		} else {
			return false;
		}
	}

	private void InitializeComponent() {

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;

		tv_qty = (TextView) findViewById(R.id.tv_qty);
		tv_tare = (TextView) findViewById(R.id.tv_tare);
		tv_tare_num = (TextView) findViewById(R.id.tv_tare_num);
		tv_qty.setText("1");

		tv_shift = (TextView) findViewById(R.id.tv_shift);

		mListView = (ListView) findViewById(R.id.lv_list);
		mAdapter = new SaleListViewAdapter(this);
		mAdapter.setDataSource(TransactionManager.getInstance().mSaleListItems);
		mAdapter.setListView(mListView);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(onItemClickListener);

		tvLabelPrice = (TextView) findViewById(R.id.tvLabelPrice);
		tvLabelPrice.setText(String.format(this.getResources().getString(R.string.label_price), GlobalInfo.getInstance().CurrencySymbol));

		tvLabelSubtotal = (TextView) findViewById(R.id.tvLabelSubtotal);
		tvLabelSubtotal.setText(String.format(this.getResources().getString(R.string.label_subtotal), GlobalInfo.getInstance().CurrencySymbol));

		tvLabelDiscount = (TextView) findViewById(R.id.tvLabelDiscount);
		tvLabelDiscount.setText(String.format(this.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));

		tvSubTotal = (TextView) findViewById(R.id.tv_subtotal_num);
		tvTax = (TextView) findViewById(R.id.tv_tax_num);

		tvLabelTax = (TextView) findViewById(R.id.tvLableTax);
		tvLabelTax.setText(String.format(this.getResources().getString(R.string.label_tax), GlobalInfo.getInstance().CurrencySymbol));

		tvTotal = (TextView) findViewById(R.id.tv_total_num);
		tvLabelTotal = (TextView) findViewById(R.id.tvLabelTotal);
		tvLabelTotal.setText(String.format(this.getResources().getString(R.string.label_total), GlobalInfo.getInstance().CurrencySymbol));

		tvCashier = (TextView) findViewById(R.id.tv_cashier_num);
		tvCashier.setText("Cashier: " + GlobalInfo.getInstance().cashier);
		tvDiscount_num = (TextView) findViewById(R.id.tv_discount_num);
		tvDiscount = (TextView) findViewById(R.id.tvLabelDiscount);
		tvDiscount.setText(String.format(this.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));

		tvtrnstype = (TextView) findViewById(R.id.tv_trns_type);
		
		tvsptrnstype = (TextView) findViewById(R.id.tv_sp_trns_type);
		
		btnExit = (Button) findViewById(R.id.buttonSaleExit);
		btnExit.setOnClickListener(OnClickControlListener);

		btnSaleOpenDepItem = (Button) findViewById(R.id.buttonSaleOpenDepartment);
		btnSaleOpenDepItem.setOnClickListener(OnClickControlListener);

		btnFunction = (Button) findViewById(R.id.buttonSaleFunction);
		btnFunction.setOnClickListener(OnClickControlListener);

		btnHotpick = (Button) findViewById(R.id.buttonSaleHotpick);
		btnHotpick.setOnClickListener(OnClickControlListener);

		btnSubtotal = (Button) findViewById(R.id.buttonSaleSubtotal);
		btnSubtotal.setOnClickListener(OnClickControlListener);

		tvDiscount_num.setVisibility(View.INVISIBLE);
		tvDiscount.setVisibility(View.INVISIBLE);

		// set default image
		ivProductPic = (ImageView) findViewById(R.id.iv_photo);
		ivProductPic.setImageResource(R.drawable.moleqlogo);

		// 閸旂姾娴囬弫鏉跨摟闁款喚娲�
		mNumberPad = (NumberPad) this.findViewById(R.id.NumberPadSale);
		mNumberPad.setStyle(NumberPad.SALE_STYLE);
		mNumberPad.setNumberPadListener(mNumberPadListener);
		mNumberPad.requestFocusFromTouch();

		// 閸旂姾娴囬柨?鏁崚妤勩�
		mFlipChartPanel = new FlipChartPanel(this, screenWidth, screenHeight);
		mFlipChartPanel.setOnTouchSaleItemListener(mOnTouchFlipChartListener);

	}

	private void ProcessFuncation(int funcId, Object obj) {

		String parm1;
		int parm2;
		switch (funcId) {

		case MoleQConstants.FUNCTION_SHIFT_FOODSTAMP:
			//
			if (mCurrentFunctionOption != null) {

				mTransMgr.shiftFs = !mTransMgr.shiftFs;
				refreshDisplayContent();
				mTransMgr.SaveFreeFuncRpt(FreeFuncRpt.SHIFT_FOODSTAMP, 1, 0);
				mPosSender.send("SHIFT FOODSTAMP");
			}

			break;
		case MoleQConstants.FUNCTION_SHIFT_TAX:
			if (mCurrentFunctionOption != null) {
				int num = mCurrentFunctionOption.getTp_parameter2();

				if (mTransMgr.shiftNum == num) {
					num = -1;
				}
				mTransMgr.shiftNum = num;
				refreshDisplayContent();

				mTransMgr.SaveFreeFuncRpt(FreeFuncRpt.SHIFT_TAX, 1, 0);
				if (num != 0) {
					mPosSender.send("SHIFT TAX"+num);
				}else if(num == 0){
					mPosSender.send("SHIFT TAX ALL");
				}else{
					mPosSender.send("CLOSE SHIFT TAX");
				}
			}

			break;
		case MoleQConstants.FUNCTION_VOID:

			GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_VOID;
			if (mTransMgr.mSaleListItems.getItemCount() == 0) {
				// setDeleteMode(false);
				mDeleteMode = false;
				mAdapter.setShowControl(mDeleteMode);
				return;
			}

			if (mDeleteMode) {
				mDeleteMode = false;
			} else {
				mDeleteMode = true;
			}
			mAdapter.setShowControl(mDeleteMode);

			break;
		case MoleQConstants.FUNCTION_ERROR_CORRECT:
			GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_ERROR_CORRECT;

			final int row = mTransMgr.mSaleListItems.getItemCount() - 1;
			if (row < 0)
				return;
			
			OnClickMessageListener mOnECClickMessageListener = new OnClickMessageListener() {

				@Override
				public void onClickYes() {
					SaleListItem item = mTransMgr.mSaleListItems.getItem(row);
					
					deleteVdrCoupon(item);
					mTransMgr.mSaleListItems.remove(row);
//					mPosSender.send("VOID "+item.getName() +"   "
//							+MoleQUtil.fixPriceForScreen(item.getPrice()));
				}

				@Override
				public void onClickNo() {
				}

				@Override
				public void onClickOK() {
				}

			};
			
			if (mTransMgr.mSaleListItems.canSingleDeleteItem(row)) {
				String msg = "Do you want to remove the ";
				if (mTransMgr.mSaleListItems.getItem(row).getItemType() == ItemType.ITEM_COUPON) {
					msg += "item coupon?";
				}else if(mTransMgr.mSaleListItems.getItem(row).getItemType() == ItemType.VDR_COUPON){
					msg = "Are you sure to remove the vendor coupon?";
				}else{
					msg += "item discount?";
				}
//				SaleListItem item = mTransMgr.mSaleListItems.getItem(row);
//				if(item.getItemType() == ItemType.VDR_COUPON){
//					if(item.getParentId() == null || item.getParentId().equals("")){
//						for (int i = (row + 1); i < mTransMgr.mSaleListItems.getItemCount(); i++) {
//							SaleListItem item2 = mTransMgr.mSaleListItems.getItem(i);
//							if(item.getUpc().equals(item2.getUpc())){
//								if(row < i){
//									msg = "Last In First Out.Please delete the last entered vendor coupon.";
//									MessageBox.show(SaleActivity.this, msg, mOnECClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
//									return;
//								}
//							}
//						}
//					}else{
//						int index = mTransMgr.mSaleListItems.findByParent(item.getParentId());
//						SaleListItem item2 = mTransMgr.mSaleListItems.getItem(index);
//						for (int i = (row + 1); i < mTransMgr.mSaleListItems.getItemCount(); i++) {
//							SaleListItem item3 = mTransMgr.mSaleListItems.getItem(i);
//							if(item2.getUpc().equals(item3.getUpc())){
//								if(row < i){
//									msg = "Last In First Out.Please delete the last entered vendor coupon.";
//									MessageBox.show(SaleActivity.this, msg, mOnECClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
//									return;
//								}
//							}
//						}
//					}
//				}
				MessageBox.show(this, msg, mOnECClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
				return;
			}
			SaleListItem item = mTransMgr.mSaleListItems.getItem(row);
			if(item.getItemType() == ItemType.PACKAGE_PRICE_FIX || 
					item.getItemType() == ItemType.LIMITED_QTY_PRICE_FIX || 
					item.getItemType() == ItemType.DISCOUNT_AMOUNT || 
					item.getItemType() == ItemType.DISCOUNT_PERECENT ||
					item.getItemType() == ItemType.DISCOUNT_LINK){
				int index = mTransMgr.mSaleListItems.findByParent(item.getParentId());
				SaleListItem item2 = mTransMgr.mSaleListItems.getItem(index);
				String[] Vdr = item2.getVdrCouponBarcode();
				for (int i = 0; i < Vdr.length; i++) {
					if(Vdr[i] != null && Vdr[i].length() > 0 && !Vdr[i].equals("Vdr Coupon") && !Vdr[i].equals("Mult Vdr Coupon") && !Vdr[i].equals("Add Value")){
						String msg = "Please remove the vendor coupon first.";
						MessageBox.show(this, msg, mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
						return;
					}
				}
			}else{
				String[] Vdr = item.getVdrCouponBarcode();
				for (int i = 0; i < Vdr.length; i++) {
					if(Vdr[i] != null && Vdr[i].length() > 0 && !Vdr[i].equals("Vdr Coupon") && !Vdr[i].equals("Mult Vdr Coupon") && !Vdr[i].equals("Add Value")){
						String msg = "Please remove the vendor coupon first.";
						MessageBox.show(this, msg, mOnClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
						return;
					}
				}
			}
			SaleListItem item2 = mTransMgr.mSaleListItems.getItem(row);
			deleteVdrCoupon(item2);
			mTransMgr.mSaleListItems.removeItem(row);
//			mPosSender.send("VOID "+item.getName() +"   "
//							+MoleQUtil.fixPriceForScreen(item.getPrice()));
			mTransMgr.mSaleListItems.hightLightBottomItem();
			break;
		case MoleQConstants.FUNCTION_TARE:
			
			 parm1 = mCurrentFunctionOption.getTp_parameter1();
			 parm2 = mCurrentFunctionOption.getTp_parameter2();
			
			if (parm1.equals(FunctionPanel.MANUAL_TARE) ) {
				DialogManager.show(this, DialogManager.TARE_INFO);
			}else if (parm1.equals(FunctionPanel.UNIT_OF_TARE)) {
				if (parm2 > 0) {
					mTransMgr.manualTare = Integer.valueOf(parm2) ;	
					GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_TARE;
					refreshDisplayContent();
				}
			}

			break;
		case MoleQConstants.FUNCTION_GLOBAL_DISCOUNT:

			if (mCurrentFunctionOption != null) {

				 parm1 = mCurrentFunctionOption.getTp_parameter1();
				 parm2 = mCurrentFunctionOption.getTp_parameter2();
				 GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_DISCOUNT;
					
				switch (parm2) {
				case FunctionPanel.GLOBAL_DISCOUNT_MANUAL_PERCENT:
					// open input percent dialog
					GlobalDiscountManualDialog mGlobalDiscountManualDialog = new GlobalDiscountManualDialog(this,this);
					//mGlobalDiscountManualDialog.setMode(FunctionPanel.GLOBAL_DISCOUNT_MANUAL_PERCENT);
					mGlobalDiscountManualDialog.show();
					break;
				case FunctionPanel.GLOBAL_DISCOUNT_REMOVE:
					// Remove input percent dialog
					if (mTransMgr.TransDntValue > 0) {
						mTransMgr.mSaleListItems.removeGlobalDiscount();
						refreshDisplayContent();
					}
					break;
				default:
					// find link global discount
					GlobalDiscountSetting mGlobalDiscountSetting = ServiceManager.getInstance().mGlobalDiscountSettingService.Find(parm2);
					if (mGlobalDiscountSetting != null) {
						mTransMgr.mSaleListItems.addGlobalDiscount(mGlobalDiscountSetting.getGd_value());
						refreshDisplayContent();
					}
					break;
				}
				// TODO Auto-generated method stub wei.

			}

			// DialogManager.show(this, DialogManager.TRANS_DISCOUNT);
			break;

		case MoleQConstants.FUNCTION_TAX_EXEMPT:
			if (mCurrentFunctionOption != null) {
				
				if(mTransMgr.mSaleListItems.getItemCount() <= 0) return;
				parm2 = mCurrentFunctionOption.getTp_parameter2();
				if (parm2 == mTransMgr.mTaxExempat) {
					mTransMgr.mTaxExempat = -1;

				}else{
					mTransMgr.mTaxExempat = parm2;
				}
				mTransMgr.mSaleListItems.useTaxExempt(parm2);
				if (parm2 == 0) {
					mPosSender.send("EXEMPT TAX ALL");
				}else{
					mPosSender.send("EXEMPT TAX " + parm2);
				}
			}
			break;

		case MoleQConstants.FUNCTION_REFUND:
			if (mTransMgr.TransType == TransactionType.WIC) return;
			
			if (mTransMgr.status == TransactionStatus.CLOSED) {

				if (mTransMgr.TransType == TransactionType.RETURN) {
					mTransMgr.TransType = TransactionType.SALE;
					GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.NONE;
				} else {
					mTransMgr.TransType = TransactionType.RETURN;
					GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_REFUND;
					mPosSender.sendRed(MoleQUtil.getSenderString("TRANSACTION REFUND"));
				}
				mTransMgr.mSaleListItems.announceCartChanges();
			} else {
				// MessageBox.show(this,
				// "Refund transaction is not allowed when there is a transaction pending for completion.");
				if (mTransMgr.TransType != TransactionType.RETURN) {
					if (mRefundMode) {
						mRefundMode = false;
					} else {

						mRefundMode = true;
						mPosSender.sendRed(MoleQUtil.getSenderString("REFUND"));
					}
				}
				
				mTransMgr.mSaleListItems.announceCartChanges();

			}

			break;
		case MoleQConstants.FUNCTION_CUSTOMER:
			//
			break;
		case MoleQConstants.FUNCTION_PRICE_CHANGE:
			if (mTransMgr.canUsePriceChange()) {
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_PRICE_CHANGE;
				DialogManager.show(this, DialogManager.PRICE_CHANGE);
			}
			break;
		case MoleQConstants.FUNCTION_ITEM_DISOCUNT:
			if (mCurrentFunctionOption != null) {
				if (mTransMgr.canUseItemDiscount()) {
					 parm1 = mCurrentFunctionOption.getTp_parameter1();
					 parm2 = mCurrentFunctionOption.getTp_parameter2();
					 
					 int itemIdx = mTransMgr.mSaleListItems.getSelectedRegularItemIdx();
					 SaleListItem selectitem = null;
						if (itemIdx >= 0) {
							 selectitem = mTransMgr.mSaleListItems.getItem(itemIdx);
						}
					if(selectitem != null && selectitem.getNodiscount()){
						MessageBox.show(SaleActivity.this, "No discount for the item.");
						return;
					}
							
					switch (parm2) {
					case FunctionPanel.ITEM_DISCOUNT_MANUAL_PERCENT:
						// open input percent dialog
						ItemDiscountManualDialog percentDiscontDialong = new ItemDiscountManualDialog(this,this);
						percentDiscontDialong.setMode(FunctionPanel.ITEM_DISCOUNT_MANUAL_PERCENT);
						percentDiscontDialong.show();
						break;
					case FunctionPanel.ITEM_DISCOUNT_MANUAL_AMOUNT:
						// open input amount dialog
						ItemDiscountManualDialog amountDiscontDialong = new ItemDiscountManualDialog(this,this);
						amountDiscontDialong.setMode(FunctionPanel.ITEM_DISCOUNT_MANUAL_AMOUNT);
						amountDiscontDialong.show();
						break;
					default:
						// find link global discount
						ItemDiscountSetting discount = ServiceManager.getInstance().mDiscountSettingService.Find(parm2);
						if (discount != null) {
							mTransMgr.mSaleListItems.addItemDiscount(0,discount,parm2);
						}
						break;
					}

				}

			}

			break;
		case MoleQConstants.FUNCTION_CANCEL:
//			GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_CANCEL;
//			if (mTransMgr.status == TransactionStatus.STARTED) {
//
//				if (mTransMgr.tenderList.size() > 0) {
//					MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_cancel_trans_error));
//					return;
//				}
//
//				MessageBox.show(this, getResources().getString(R.string.msg_cancel_trns), mFuncCancellistener, MessageDialog.MESSAGE_BOX_YES_NO);
//			}
			mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, mTransMgr.getSubTotal());
			mTransMgr.CancelTransaction();

			Printer printer = DeviceManager.getInstance().ReceiptPrinter;
			PrinterBufferRowColection printBuffer = ReceiptManager.getCancelTrnReceipt(GlobalInfo.getInstance().cashier, mTransMgr);
			printer.open();
			if (printer.isEnable() && !printer.isBusy() && !printer.ismOutOfPaper()) {
				printer.setPrinterBuffer(printBuffer);
				printer.print();
				printer.cutPaper();
			}
			printer.close();
			mTransMgr.SaveEJ(printBuffer.toReceipt());
			mRefundMode = false; // cancel refund
			mDeleteMode = false;
			mAdapter.setShowControl(mDeleteMode);
			mTransMgr.Reset();
			mTransMgr.announceChanges();
			refreshDisplayContent();
			break;
		case MoleQConstants.FUNCTION_NO_SALE:
//			GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_NO_SALE;
//			if (mTransMgr.status == TransactionStatus.CLOSED) {
//				MessageBox.show(this, getResources().getString(R.string.msg_no_sale), mNoSalelistener, MessageDialog.MESSAGE_BOX_YES_NO);
//			} else {
//				MessageBox.show(this, getResources().getString(R.string.msg_no_sale_error));
//			}
			
			mRefundMode = false; //cancel refund
			GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);	
			
			mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, 0);
			mTransMgr.NoSaleTransaction();

			Printer printer2 = DeviceManager.getInstance().ReceiptPrinter;
			PrinterBufferRowColection printBuffer2 = ReceiptManager.getNoSaleReceipt(GlobalInfo.getInstance().cashier, mTransMgr);
			printer2.open();
			if (printer2.isEnable() && !printer2.isBusy() && !printer2.ismOutOfPaper()) {
				printer2.setPrinterBuffer(printBuffer2);
				printer2.print();
				printer2.cutPaper();
			}
			printer2.close();
			mTransMgr.SaveEJ(printBuffer2.toReceipt());
			
			mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
			mTransMgr.CompleteTransaction();
			mTransMgr.Reset();
			
			// ProcessFuncClick(FunctionOption.OPEN_CASH_DRAWER);
			ProcessFuncation(MoleQConstants.OPEN_CASH_DRAWER, "");
			break;

		case MoleQConstants.FUNCTION_COUPON:
			if(mCurrentFunctionOption != null){
				if (mTransMgr.canUseItemCoupon()) {
					
					 parm1 = mCurrentFunctionOption.getTp_parameter1();
					//int parm2 = mCurrentFunctionOption.getTp_parameter2();
					double parm3 = mCurrentFunctionOption.getTp_parameter3();
					
					if (parm1.equals(FunctionPanel.COUPON_PERCENT)) {
						// add coupon to sale list for percent
						mTransMgr.mSaleListItems.addItemCoupon(parm3, FunctionPanel.COUPON_PERCENT);
					}if (parm1.equals(FunctionPanel.COUPON_AMOUNT)) {
						// add coupon to sale list for amount
						mTransMgr.mSaleListItems.addItemCoupon(parm3, FunctionPanel.COUPON_AMOUNT);
						
					}if (parm1.equals(FunctionPanel.COUPON_MANUAL_PERCENT)) {
						// open input manual percent dialog
						ItemCouponDialog percentdialog = new ItemCouponDialog(this);
						percentdialog.setMode(FunctionPanel.COUPON_MANUAL_PERCENT);
						percentdialog.show();
					}if (parm1.equals(FunctionPanel.COUPON_MANUAL_AMOUNT)) {
						// open input manual amount dialog
						ItemCouponDialog amountdialog = new ItemCouponDialog(this);
						amountdialog.setMode(FunctionPanel.COUPON_MANUAL_AMOUNT);
						amountdialog.show();
					}
					
					mRefundMode = false; //cancel refund
					GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);	
				}
			}
			break;

		case MoleQConstants.START_TRANSACTION:

			mDeviceManager.enableAllScanner();

			this.StartTransaction();

			break;

		case MoleQConstants.PAYMENT_CHECK_OUT:
			DialogManager.show(this, DialogManager.CHECK_OUT);

			mCurrentApproval = MoleQConstants.STATE_FUNCTION_APPROVAL;
			mTransMgr.CompleteTransaction();
			mRefundMode = false;
			break;
		case MoleQConstants.OPEN_CASH_DRAWER:
			new Thread(new Runnable() {
				public void run() {
					Drawer dr = new Drawer();
					dr.open(DeviceCommon.DEVICE_MODE_COMMON, null);
					dr.setOpen(Drawer.DEVICE_DRAWER_NO1);
					dr.close();
				}
			}).start();
			break;
		case MoleQConstants.PRINT_RECEIPT:
			// new Thread(new Runnable(){
			// public void run(){
			// printReceipt();
			// }
			// }).start();
			// final PosPrinter printer = (PosPrinter)mDeviceManager.printer;
			
			DialogManager.show(SaleActivity.this, DialogManager.PROCESSING_PRINT_RECEIPT);
			
			final Printer printer3 = DeviceManager.getInstance().ReceiptPrinter;
			new Thread(new Runnable() {
				public void run() {

					try {
						printer3.open();
						if (printer3.isEnable() && !printer3.isBusy() && !printer3.ismOutOfPaper()) {

							if (mTransMgr.isNeedSignature()) {
								ArrayList<PosTender> tendrs = mTransMgr.getTendersByPaymentType(PaymentType.CREDIT_CARD);
								for (int i = 0; i < tendrs.size(); i++) {
									if (tendrs.get(i).isNeedPrint && tendrs.get(i).getPt_tender() >= GlobalInfo.getInstance().sigMinValue) {
										PrinterBufferRowColection printBuffer1 = ReceiptManager.getSignature(mTransMgr.TransactionNo, mTransMgr.dDoneDate, GlobalInfo.getInstance().cashier, tendrs.get(i), mTransMgr.isReprint);
										printer3.setPrinterBuffer(printBuffer1);
										printer3.print();
										printer3.cutPaper();
									}
								}
							}
							printer3.close();
							printer3.open();
							PrinterBufferRowColection printBuffer2 = ReceiptManager.getSaleReceipt(GlobalInfo.getInstance().cashier, mTransMgr);
							printer3.setPrinterBuffer(printBuffer2);
							printer3.print();
							printer3.cutPaper();
						}
						printer3.close();
						
						//print service item
						if (mTransMgr.haveServiceItem() && GlobalInfo.getInstance().isPrintServiceItem
								&& !MoleQUtil.getTransType(mTransMgr.TransType).equals("R")) {
							
							List<SaleListItem> listItem = new ArrayList<SaleListItem>();
							
							//print local
							listItem = mTransMgr.getServiceItemAllList();
							printer3.open();
							if (printer3.isEnable() && !printer3.isBusy() && !printer3.ismOutOfPaper()) {
								PrinterBufferRowColection printBuffer3 = ReceiptManager.getServiceTicketLocalReceipt(GlobalInfo.getInstance().cashier, mTransMgr, listItem);
								printer3.setPrinterBuffer(printBuffer3);
								printer3.print();
								printer3.cutPaper();
							}
							printer3.close();
							
							if (!mTransMgr.isReprint) {
								//print none
								listItem = mTransMgr.getServiceItemListByID(0);
								printer3.open();
								if (printer3.isEnable() && !printer3.isBusy() && listItem.size() > 0 && !printer3.ismOutOfPaper()) {
									PrinterBufferRowColection printBuffer4 = ReceiptManager.getServiceItemReceipt(GlobalInfo.getInstance().cashier, mTransMgr, listItem);
									printer3.setPrinterBuffer(printBuffer4);
									printer3.print();
									printer3.cutPaper();
								}
								printer3.close();
								
								List<PrinterSetting> listPrinter = ServiceManager.getInstance().mPrinterSettingService.FindAll();
								
								for (int i = 0; i < listPrinter.size(); i++) {
									listItem = mTransMgr.getServiceItemListByID(listPrinter.get(i).getPs_id());
									if (listItem.size() == 0) continue;
									
									Printer svrPrinter = DeviceManager.getInstance().ServiceTicketPrinters.get(listPrinter.get(i).getPs_id());
									svrPrinter.open();
									if (svrPrinter.isEnable()) {
										PrinterBufferRowColection prinerBuffer = ReceiptManager.getServiceItemReceipt(GlobalInfo.getInstance().cashier,mTransMgr,listItem);
										svrPrinter.setPrinterBuffer(prinerBuffer);
										svrPrinter.print();
										svrPrinter.cutPaper();
										svrPrinter.close();
									}else {
										svrPrinter.close();
										
										printer3.open();
										if (printer3.isEnable() && !printer3.isBusy() && !printer3.ismOutOfPaper()) {
											PrinterBufferRowColection printBuffer5 = ReceiptManager.getServiceItemReceipt(GlobalInfo.getInstance().cashier, mTransMgr, listItem);
											printer3.setPrinterBuffer(printBuffer5);
											printer3.print();
											printer3.cutPaper();
											printer3.close();
										}
									}
								}
							}
						}
						mTransMgr.isReprint = true;
						DialogManager.hide(DialogManager.PROCESSING_PRINT_RECEIPT);
					} catch (Exception e) {
						// TODO: handle exception
						MessageBox.show(SaleActivity.this, e.getMessage());
					}
					

				}
			}).start();
			break;
			
		case MoleQConstants.FUNCTION_WIC:
			//WIC transaction
			if (mTransMgr.TransType == TransactionType.CVV) return;
			if (mCurrentFunctionOption != null) {
				
				 parm2 = mCurrentFunctionOption.getTp_parameter2();
				
				switch (parm2) {
				case FunctionPanel.WIC_NEW_EDIT:
					if (mTransMgr.status != TransactionStatus.CLOSED && mTransMgr.TransType != TransactionType.WIC && mTransMgr.mSaleListItems.getItemCount() > 0){
						MessageBox.show(this, getResources().getString(R.string.msg_wic_error));
						return;
					}
					DialogManager.show(SaleActivity.this, DialogManager.WIC);
					break;
				case FunctionPanel.WIC_REMOVE:
					if (mTransMgr.mSaleListItems.getItemCount() > 0 &&  mTransMgr.TransType == TransactionType.WIC) {
						MessageBox.show(SaleActivity.this, getResources().getString(R.string.msg_del_wic_item));
						return;
					}
					mTransMgr.TransType = TransactionType.SALE;
					mTransMgr.CVVWicPrice = 0;
					refreshDisplayContent();
					ServiceManager.getInstance().mPosLineCvvWicService.DeleteByAll();
					break;
				default:
					break;
				}
			}
			break;
		case MoleQConstants.FUNCTION_CVV:
			//CVV transaction
			if (mTransMgr.TransType == TransactionType.WIC) return;
			if (mCurrentFunctionOption != null) {
				
				 parm2 = mCurrentFunctionOption.getTp_parameter2();
				
				switch (parm2) {
				case FunctionPanel.CVV_NEW_EDIT:
					if (mTransMgr.status != TransactionStatus.CLOSED && mTransMgr.mSaleListItems.getItemCount() > 0 && mTransMgr.TransType != TransactionType.CVV){
						MessageBox.show(this, getResources().getString(R.string.msg_cvv_error));
						return;
					}
					DialogManager.show(SaleActivity.this, DialogManager.CVV);
					break;
				case FunctionPanel.CVV_REMOVE:
					if (mTransMgr.mSaleListItems.getItemCount() > 0 &&  mTransMgr.TransType == TransactionType.CVV) {
						MessageBox.show(SaleActivity.this, getResources().getString(R.string.msg_del_cvv_item));
						return;
					}
					mTransMgr.TransType = TransactionType.SALE;
					mTransMgr.CVVWicPrice = 0;
					refreshDisplayContent();
					ServiceManager.getInstance().mPosLineCvvWicService.DeleteByAll();
					break;
				default:
					break;
				}
			}
			break;
		case MoleQConstants.FUNCTION_SIGN_OUT:
//			GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_SIGN_OUT;
//			if (mTransMgr.status == TransactionStatus.CLOSED) {
//				
//				MessageBox.show(this, getResources().getString(R.string.msg_sign_out), mSignOutlistener, MessageDialog.MESSAGE_BOX_YES_NO);
//			}else{
//				MessageBox.show(this, getResources().getString(R.string.msg_sign_out_error));
//				return;
//			}
			mRefundMode = false; //cancel refund
			mTransMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_SIGN_OUT, 1, 0);
			mPosSender.sendRed(MoleQUtil.getSenderString("SIGN OUT"));
			
			mTransMgr.TransType = TransactionType.SALE;
			mTransMgr.Reset();
			dispose();
			finish();
			
			
//			GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);	
			break;
		}
	}

	public void showImage(Bitmap bm) {

		if (ivProductPic != null) {
			if (bm == null) {
				// ivProductPic.setImageResource(R.drawable.moleqlogo);
				bm = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.moleqlogo);
			}
			ivProductPic.setImageBitmap(bm);
		}
	}

	public void keySearchItem(UPC upc) {

//		if (currentQty == 1){
		currentQty = mNumberPad.getQty();
//		}

		mNumberPad.setQty(1);

		String inputText = upc.code;

		if (mDeleteMode) {

			int totalQty = mTransMgr.mSaleListItems.getQtyByUPC(inputText);
			if (totalQty == 0) {
				MessageBox.show(this, getResources().getString(R.string.msg_del_item_no_qty), mOnClickMessageListener);
				return;
			}
			if (totalQty < currentQty) {
				MessageBox.show(this, String.format(getResources().getString(R.string.msg_del_item_not_enough), totalQty), mOnClickMessageListener);
				return;
			}
//			if (mTransMgr.mSaleListItems.checkIsLastItem(deletePosition)) {
//				
//				mPosSender.sendRed("VOID");
//				deleteVdrCoupon(mTransMgr.mSaleListItems.getItem(deletePosition));
//				mTransMgr.mSaleListItems.removeItem(deletePosition);
//				// setDeleteMode(false);
//				mDeleteMode = false;
//				mAdapter.setShowControl(mDeleteMode);
//				
//			} else {
//				MessageBox.show(this, this.getResources().getString(R.string.msg_del_last_item));
//			}
			mTransMgr.mSaleListItems.removeItemByUPC(inputText, currentQty);
			mTransMgr.mSaleListItems.hightLightBottomItem();
			// this.setDeleteMode(false);
			mDeleteMode = false;
			mAdapter.setShowControl(mDeleteMode);

		} else {
			// itemTare = 0;
			// creator.buildItemByUpc( inputText,currentQty);

			mSaleListitem = mTransMgr.mSaleListItems.createItem();
			mSaleListitem.setUpc(inputText);
			mSaleListitem.setRefund(mRefundMode);

			Product product = mProductService.Find(inputText);

			if (product != null && product.getIsActive().equals("A")) {
				// String ls_taxdesc = "";
				mSaleListitem.setItemType(ItemType.REGULAR);
				mSaleListitem.setName(product.getName1());
				mSaleListitem.setDisplayContent(product.getName1());
				mSaleListitem.setDescription(product.getDesc());
				mSaleListitem.setBottleDeposit(product.getBottle_deposit());
				mSaleListitem.setTareCount(ServiceManager.getInstance().mTareSettingService.HaveTare(product.getBarcode()));
				mSaleListitem.setDep(product.getDep());
				mSaleListitem.setFollowdep(product.getFollowdep());
				mSaleListitem.setTax1(product.getTax1());
				mSaleListitem.setTax2(product.getTax2());
				mSaleListitem.setTax3(product.getTax3());
				mSaleListitem.setTax4(product.getTax4());
				mSaleListitem.setTax5(product.getTax5());
				mSaleListitem.setTax6(product.getTax6());
				mSaleListitem.setIsWeight(product.isWeight());
				mSaleListitem.setFoodstamp(product.getFoodstamp());
				mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(product.getAgeLinkNo()));
				mSaleListitem.setNodiscount(product.getNodiscount());
				mSaleListitem.setUpc(product.getBarcode());
				mSaleListitem.setUnitPrice(product.getPrice());
				mSaleListitem.setQty(currentQty);
				mSaleListitem.setPkgItem(upc.IsPackageItem);
				mSaleListitem.setIscoupon(product.getIscoupon());
				if (mSaleListitem.getIscoupon()) {
					mSaleListitem.setItemType(ItemType.COUPON);
				}
				mSaleListitem.setIsMultCoupon(product.getIs_mult_coupon());
				mSaleListitem.setWic(product.isWic());
				mSaleListitem.setCvv(product.isCvv());
				mSaleListitem.setServiceItem(product.isServiceItem());
				mSaleListitem.setPrinter_id(product.getPrinter_id());
				mSaleListitem.setVdr_code(inputText.substring(2, 7));
				mSaleListitem.setFam_code(inputText.substring(7, 10));
				mSaleListitem.setVdr_coupon_code_no(inputText.substring(10, 12));
				String vdrCouponBarcode = CheckVdrCoupon(inputText);
//				ads;
				if(!vdrCouponBarcode.equals("")){
					String[] VdrCoupon = new String[currentQty];
					for (int i = 0; i < VdrCoupon.length; i++) {
						VdrCoupon[i] = vdrCouponBarcode;
					}
					mSaleListitem.setVdrCouponBarcode(VdrCoupon);
				}
				if (mTransMgr.TransType == TransactionType.WIC && !mSaleListitem.isWic()){
					MessageBox.show(this, "WIC-eligible Foods Only.");
					return;
				}
				
				if (mTransMgr.TransType == TransactionType.CVV && !mSaleListitem.isCvv()){
					MessageBox.show(this, "CVV-eligible Foods Only.");
					return;
				}
				// check package item
				if (mSaleListitem.getPkgItem()) {
					// mSaleListitem.setPkgitemno(upc.code);
					mSaleListitem.setQty(1);
					mSaleListitem.setItemType(ItemType.PACKAGE_ITEM);
					double tmpP4 = BigDecmialTool.div(Double.valueOf(upc.PackageItemPrice), 100);
					double tmpUnitP4 = product.getPrice();
					int cutQty = product.getCurrentPriceQty();
					tmpUnitP4 = BigDecmialTool.div(tmpUnitP4, cutQty);
					double tmpWeight = 0;
					mSaleListitem.setPrice(tmpP4);
					if (tmpUnitP4 > 0) {
						tmpWeight = BigDecmialTool.div(tmpP4, tmpUnitP4);
						tmpWeight = BigDecmialTool.round(tmpWeight, mGlobalInfo.decimalPoint);
						mSaleListitem.setBaseweight(tmpWeight);
						mSaleListitem.setWeight(tmpWeight);
						mSaleListitem.setUnitPrice(tmpUnitP4);
						// mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(tmpWeight,
						// getUnit()) + weight_unit);
					}
				} else {

					if (!mSaleListitem.getIscoupon()) {
						PriceSetting setting = mPriceService.getitemprice(mSaleListitem.getUpc());
						if (setting != null && setting.haveMixAndMatch && !mSaleListitem.getIsWeight()) {
							String mmNum = setting.getPricemm();
							setting = ServiceManager.getInstance().mMixMatchService.findSettingByUpc(mSaleListitem.getUpc());
							if (setting != null) {
								setting.setPricemm(mmNum);
								setting.isMixAndMatch = true;
								mSaleListitem.setMixMatch(mmNum);
								mSaleListitem.setMixMatchDesc(" MM ");
							}
						}
						mSaleListitem.setPriceSetting(setting);
					}
					// set price setting

				}

				// set bottledeposit setting
				if (mSaleListitem.getBottleDeposit() > 0) {
					mBottleSetting = ServiceManager.getInstance().mBottleSettingService.Find(mSaleListitem.getBottleDeposit());
					if (mBottleSetting != null) {
						mSaleListitem.setmBottleSeting(mBottleSetting);
					}
				}

				// set tax1 , tax2 ,tax3 ,tax4
				deptSetting = mSubDepartmantService.Find(mSaleListitem.getDep());
				if (deptSetting != null) {

					mSaleListitem.setDep_group(mSubDepartmantService.getGroupNobyid(deptSetting.getSd_id()));
					mSaleListitem.setMdepartment(mSubDepartmantService.getDepNoById(deptSetting.getSd_id()));
				}

				if (mSaleListitem.getFollowdep() && deptSetting != null) {
					mSaleListitem.setTax1(deptSetting.getTax1());
					mSaleListitem.setTax2(deptSetting.getTax2());
					mSaleListitem.setTax3(deptSetting.getTax3());
					mSaleListitem.setTax4(deptSetting.getTax4());
					mSaleListitem.setTax5(deptSetting.getTax5());
					mSaleListitem.setTax6(deptSetting.getTax6());
					mSaleListitem.setIsWeight(deptSetting.getScale_weight());
					mSaleListitem.setFoodstamp(deptSetting.getFood_stamp());
					mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(deptSetting.getAge()));
					mSaleListitem.setNodiscount(deptSetting.getNo_discnt());
					mSaleListitem.setWic(deptSetting.isWic());
					mSaleListitem.setCvv(deptSetting.isCvv());
				}

				// shiftTax(mSaleListitem);
				//
				// shiftFoodStamp(mSaleListitem);

				ProcessedAge();
			}else {

				SmartBeep.getInstance().play(SmartBeep.SOUND_ERROR);

				MessageBox.show(this, getResources().getString(R.string.msg_item_not_found), mOnClickMessageListener);

				TransactionManager.getInstance().announceChanges();
			}
		}

	}
	
	public String CheckVdrCoupon(String barcode){
		String vdr_code = barcode.substring(1, 6);
//		String fam_code = barcode.substring(6, 9);
//		String vdr_coupon_code_no = barcode.substring(9, 11);
		VdrCouponService mVdrCouponService = ServiceManager.getInstance().mVdrCouponService;
		
		for (int i = 0; i < mTransMgr.mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mTransMgr.mSaleListItems.getItem(i);
			String itemVdrCode = item.getUpc().substring(1,6);
			if(vdr_code.equals(itemVdrCode)){
				String[] vdrCoupon = item.getVdrCouponBarcode();
				for (int j = 0; j < vdrCoupon.length; j++) {
					if(vdrCoupon[j] != null && !vdrCoupon[j].equals("") && !vdrCoupon[j].equals("Vdr Coupon")
							&& !vdrCoupon[j].equals("Mult Vdr Coupon") && !vdrCoupon[j].equals("Add Value")){
						String vdr_coupon_code_no = vdrCoupon[j].substring(9, 11);
						VdrCoupon mVdrCoupon = mVdrCouponService.findVdrCouponById(vdr_coupon_code_no);
						if(mVdrCoupon.getCv_more_fl().equals("1")){
							return vdrCoupon[j];
						}
					}
				}
			}
		}
		return "";
	}

	public boolean ProcessedAge() {
		if (!mTransMgr.mLoadPendingItemMode) { 
			if (mTransMgr.Age <= 0 && mSaleListitem.getAge() > 0) {
				DialogManager.show(SaleActivity.this, DialogManager.DATE_SELECTION_DIALOG);
				return false;
			}

			if (mTransMgr.Age > 0 && mSaleListitem.getAge() > mTransMgr.Age) {
				MessageBox.show(this, this.getResources().getString(R.string.msg_not_old_enough_1));

				if (mTransMgr.mSaleListItems.getItemCount() == 0) {
					mTransMgr.Age = -1;
					ServiceManager.getInstance().mPosTrnsService.UpdateBirthday("", TransactionManager.getInstance().TransactionNo);
				}
				return false;
			}
		}

		ProcessedTare();
		return true;
	}

	private void ProcessedTare() {
		// set pos line tare
		
		if (mSaleListitem.getIsWeight() && mSaleListitem.getTareCount() > 1) {
//			if (mTareDialog == null) {
//				mTareDialog = new TareDialog(this, mSaleListitem);
//				mTareDialog.show();
//			} else {
//				if (mTareDialog.isShowing()) {
//					mTareDialog.dismiss();
//				}
//				mTareDialog = new TareDialog(this, mSaleListitem);
//				mTareDialog.show();
//			}
			
			if (mFlipChartPanel != null && mFlipChartPanel.isShowing()) {
				mFlipChartPanel.hide();
			}
			mTareDialog = new TareDialog(this, mSaleListitem);
			mTareDialog.show();
			
			return;
		}

		mTareSetting = ServiceManager.getInstance().mTareSettingService.Find(mSaleListitem.getUpc());
		if (mTareSetting != null && mTareSetting.size() > 0) {
			mSaleListitem.setmTareSetting(mTareSetting);
			double tmpTareweight = BigDecmialTool.round(mTareSetting.get(0).getTa_value() * GlobalInfo.getInstance().tareRate, mGlobalInfo.decimalPoint);
			mSaleListitem.setTareWeight(tmpTareweight);
		}

		additemdetail();

	}

	public boolean additemdetail() {
		if (!mSaleListitem.getPkgItem()) {

			if (mSaleListitem.getIsWeight()) {
				if (!mDeviceManager.scaleIsReady) {
					MessageBox.show(this, getResources().getString(R.string.msg_no_weight), mOnClickMessageListener);
					return false;
				}
				mSaleListitem.setQty(1);
				double receiveWeight = 0;
				receiveWeight = mDeviceManager.scale.getWeight();
				receiveWeight = BigDecmialTool.round(receiveWeight, mGlobalInfo.decimalPoint);

				// no weight
				if (receiveWeight == 0) {
					mDeviceManager.disableAllScanner();
					MessageBox.show(this, getResources().getString(R.string.msg_no_weight), mOnClickMessageListener);
					return false;
				}
				mSaleListitem.setBaseweight(receiveWeight);
				
				// tare larger than weight not thing to do .
				double itemTare = mSaleListitem.getTareWeight();
				if (itemTare > receiveWeight)
					return false;

				String weigthdesc = MoleQUtil.fixWeight(receiveWeight, mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit;
				if (itemTare > 0) {
					receiveWeight = receiveWeight - itemTare;
					weigthdesc = MoleQUtil.fixWeight(receiveWeight, mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit;
					mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(itemTare, mGlobalInfo.decimalPoint));
				}

				mSaleListitem.setWeight(receiveWeight);
				mSaleListitem.setPrice(mSaleListitem.getUnitPrice() * receiveWeight);
				mSaleListitem.setWeightDesc(weigthdesc);

				if (itemTare == 0 && mTransMgr.manualTare > 0) {
					double tmptare = mTransMgr.manualTare * GlobalInfo.getInstance().tareRate;
					mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(tmptare, mGlobalInfo.decimalPoint));
					mSaleListitem.setTareWeight(tmptare);
					mSaleListitem.setWeight(mSaleListitem.getWeight() - tmptare);
					mSaleListitem.setPrice(mSaleListitem.getUnitPrice() * mSaleListitem.getWeight());
					mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit);
//					}else{
//						mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit);
//					}
					TareSetting tsetting = new TareSetting();
					tsetting.setTa_no(0);
					tsetting.setQty(mTransMgr.manualTare);
					mSaleListitem.setTareCount(1);
					mTareSetting.add(tsetting);
					mSaleListitem.setmTareSetting(mTareSetting);
					GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
					mTransMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, 0);
					mTransMgr.manualTare = 0;
				}
				
				if (mSaleListitem.getItemType() == ItemType.OPEN_DEPARTMENT) {
					String currentWeightDesc = MoleQUtil.fixWeight(mSaleListitem.getWeight(), MoleQUtil.getUnit()) +  GlobalInfo.getInstance().weightUnit;
					currentWeightDesc += " @ " + GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(mSaleListitem.getUnitPrice()) + "/" + GlobalInfo.getInstance().weightUnit;
					mSaleListitem.setWeightDesc(currentWeightDesc);
					mSaleListitem.setDepDescription("  " + currentWeightDesc);
				}

			} else {
				mTransMgr.manualTare = 0;
				mSaleListitem.setBaseweight(0);
				mSaleListitem.setWeight(0);
				mSaleListitem.setPrice(mSaleListitem.getUnitPrice() * mSaleListitem.getQty());
			}

		}
		
		
		mTransMgr.mSaleListItems.addItem(mSaleListitem);
		if (mTransMgr.getAmountPayable()  > mTransMgr.CVVWicPrice  && mSaleListitem.isWic() && mTransMgr.TransType == TransactionType.WIC) {
			MessageBox.show(this, "WIC balance is too low for the item(s).");
		   int count = mTransMgr.mSaleListItems.getItemCount();
		   int row = mTransMgr.mSaleListItems.getItemCount() - 1;
			if (row >= 0){
					mTransMgr.mSaleListItems.removeItem(row);
			}
			refreshDisplayContent();
//			return false;
		}
		if (mRefundMode) {
			double amt = mTransMgr.mSaleListItems.getRefundAmountById(mSaleListitem.getId());
			mTransMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_REFUND, 1, amt);
			mTransMgr.refundCount++;
		}
		
		
		mRefundMode = false; // cancel refund
		GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.NONE;
		//Send item 
		
		TransactionManager.getInstance().announceChanges();
		return true;

	}

	private void ProcessByPriceSetting() {

		if (!mSaleListitem.getPkgItem() && !mSaleListitem.getIscoupon()) {
			PriceSetting setting = mPriceService.getitemprice(mSaleListitem.getUpc());
			if (setting != null && setting.haveMixAndMatch && !mSaleListitem.getIsWeight()) {
				String mmNum = setting.getPricemm();
				setting = ServiceManager.getInstance().mMixMatchService.findSettingByUpc(mSaleListitem.getUpc());
				if (setting != null) {
					setting.setPricemm(mmNum);
					setting.isMixAndMatch = true;
					mSaleListitem.setMixMatch(mmNum);
					mSaleListitem.setMixMatchDesc(" MM ");
				}
			}
			mSaleListitem.setPriceSetting(setting);
		}

	}

	public void onLoadPosLineItem() {

		if (mLoadItemThread == null) {
			mLoadItemThread = new Thread(new Runnable() {
				@Override
				public void run() {

					LoadPosLineItems();

				}
			});

			mLoadItemThread.setDaemon(true);
			mLoadItemThread.start();
		}

		if (mLoadItemThread.getState() != Thread.State.TERMINATED) {

		} else {

			mLoadItemThread = new Thread(new Runnable() {
				@Override
				public void run() {

					LoadPosLineItems();

				}
			});
			mLoadItemThread.setDaemon(true);
			mLoadItemThread.start();
		}

	}

	private void StartTransaction() {

		mTransMgr.Reset();
		mAdapter.notifyDataSetChanged();
		mTransMgr.mLoadPendingItemMode = false;
		mRefundMode = false;
		
		if (mDvrSetting != null && mDvrSetting.getDs_onoff().equals("1")) {
			mPosSender.Prepare();
			mPosSender.sendRed(" ");
			
		}
		onLoadPosLineItem();

	}

	private synchronized void LoadPosLineItems() {

		mPosTrns = ServiceManager.getInstance().mPosTrnsService.FindLastTrn();
		if (mPosTrns != null) {

			mTransMgr.status = TransactionStatus.STARTED;
			mTransMgr.TransactionNo = mPosTrns.getPt_no();
			mTransMgr.setBirthdayDate(mPosTrns.getPt_cmr_birthday());
			mTransMgr.needToApproval = mPosTrns.getPt_approval();
			mTransMgr.Rounding_flag = mPosTrns.getPt_rounding_fl();
			mTransMgr.Rounding = mPosTrns.getPt_rounding();
			
			 mPosLineCvvWic = ServiceManager.getInstance().mPosLineCvvWicService.Find();
			if (mPosTrns.getPt_type().equals("R")) {
				mTransMgr.TransType = TransactionType.RETURN;
			}else if(mPosTrns.getPt_type().equals("W") && mPosLineCvvWic != null){
				mTransMgr.TransType = TransactionType.WIC;
				mTransMgr.CVVWicPrice = mPosLineCvvWic.getVw_amount();
			}
			else if(mPosTrns.getPt_type().equals("C") && mPosLineCvvWic != null){
				mTransMgr.TransType = TransactionType.CVV;
				mTransMgr.CVVWicPrice = mPosLineCvvWic.getVw_amount();
			}

			List<PosLineItem> listPosLineItem = null;
			listPosLineItem = ServiceManager.getInstance().mPosLineItemService.FindAll();
			List<PosTender> listPoslineTender = ServiceManager.getInstance().mPoslineTenderService.FindAll();;
			
			if (listPoslineTender != null && listPoslineTender.size()>0) {
				mTransMgr.tenderList = listPoslineTender;
			}
			
			if (listPosLineItem != null && listPosLineItem.size() > 0) {

				Message handlerMsg = loadPosLineUpdateHandler.obtainMessage();
				handlerMsg.what = MoleQConstants.SHOW_PROCESSING;
				loadPosLineUpdateHandler.sendMessage(handlerMsg);

				Log.i("com.ming", "start load item.");
				mTransMgr.mLoadPendingItemMode = true;

				try {
					Thread.sleep(600);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				for (int i = 0; i < listPosLineItem.size(); i++) {
					mPosLineItem = listPosLineItem.get(i);
					// UPC upc = new UPC(mPosLineItem.getUpc(),
					// UPC.INPUT_BY_NONE);
					// keySearchItem(upc);
					ProcessPosLineItem(mPosLineItem);
				}

				try {
					Thread.sleep(600);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				mTransMgr.mLoadPendingItemMode = false;
				Log.i("com.ming", "stop load item.");

				long maxNo = listPosLineItem.get(listPosLineItem.size() - 1).getNo();
				ServiceManager.getInstance().mPosLineItemService.DeleteAndUpdateNo(maxNo);
				
				mTransMgr.setFoodStampPrice(mTransMgr.getFoodstampOfPaidUp());
				
				handlerMsg = loadPosLineUpdateHandler.obtainMessage();
				handlerMsg.what = MoleQConstants.REFRESH_SALE_DISPLAY;
				loadPosLineUpdateHandler.sendMessage(handlerMsg);

//				handlerMsg = loadPosLineUpdateHandler.obtainMessage();
//				handlerMsg.what = MoleQConstants.HIDE_PROCESSING;
//				loadPosLineUpdateHandler.sendMessage(handlerMsg);

			}
		}

	}

	private void ProcessPosLineItem(PosLineItem posLineItem) {

		if (posLineItem == null)
			return;

		double posLineprice = 0;
		if (posLineItem.getType().equals("Q")) {
			posLineprice = posLineItem.getPrice();
		} else {
			posLineprice = posLineItem.getPrice() > 0 ? posLineItem.getPrice() : posLineItem.getPrice() * -1;
		}
		mSaleListitem = mTransMgr.mSaleListItems.createItem();

		if (posLineItem != null && posLineItem.getUpc().substring(0, 1).equals("D")) {
			System.out.println("pos line item -> " + posLineItem.getUpc() + "");
			String currentWeightDesc = "";
			int point = posLineItem.getUpc().indexOf("|");
			int depno = Integer.valueOf(posLineItem.getUpc().substring(1,point));
			Departmant poslinedeptSetting = mDepartmantService.Find(depno);
			mSaleListitem.setRefund(posLineItem.getType().equals("R") ? true : false);
			mSaleListitem.setUnitPrice(posLineprice);
			mSaleListitem.setPrice(posLineprice);
			mSaleListitem.setWeightDesc("");
			mSaleListitem.setmTareDesc("");
			mSaleListitem.setName(poslinedeptSetting.getDep_name());
			mSaleListitem.setDisplayContent(poslinedeptSetting.getDep_name());
			mSaleListitem.setQty(posLineItem.getQty());
			mSaleListitem.setUpc(posLineItem.getUpc());
			mSaleListitem.setTax1(poslinedeptSetting.getTax1());
			mSaleListitem.setTax2(poslinedeptSetting.getTax2());
			mSaleListitem.setTax3(poslinedeptSetting.getTax3());
			mSaleListitem.setTax4(poslinedeptSetting.getTax4());
			mSaleListitem.setTax5(poslinedeptSetting.getTax5());
			mSaleListitem.setTax6(poslinedeptSetting.getTax6());
			mSaleListitem.setFoodstamp(poslinedeptSetting.getFood_stamp());
			mSaleListitem.setItemType(ItemType.OPEN_DEPARTMENT);
			mSaleListitem.setNodiscount(poslinedeptSetting.getNo_discnt());
			mSaleListitem.setPoslineno(posLineItem.getNo());
			mSaleListitem.setPoslineWeight(posLineItem.getWeight());
			mSaleListitem.setDep_group(poslinedeptSetting.getGroup_no());
			mSaleListitem.setMdepartment(poslinedeptSetting.getDep_no());
			mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(poslinedeptSetting.getAge()));
			if (posLineItem.getQty() > 1) {
				mSaleListitem.setEachDescription(MoleQUtil.fixPriceForScreen(posLineprice / posLineItem.getQty())+" EACH");
			}
			
			if (mSaleListitem.getWeight() > 0){
				mSaleListitem.setPrice(posLineprice * posLineItem.getWeight());
				currentWeightDesc = MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit;
				currentWeightDesc += " @ " + GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(posLineprice) + "/" + GlobalInfo.getInstance().weightUnit;
				mSaleListitem.setWeightDesc(currentWeightDesc);
				mSaleListitem.setDepDescription("  " + currentWeightDesc);
			}
				

			mPosLineTaresList = ServiceManager.getInstance().mPosLineTaresService.Find(mPosLineItem.getNo());
			if (mPosLineTaresList != null && mPosLineTaresList.size() > 0) {
				double poslinetare = mPosLineTaresList.get(0).getLt_qty() * GlobalInfo.getInstance().tareRate;
				if (poslinetare > 0) {
					mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(poslinetare, mGlobalInfo.decimalPoint));
				}
			}
//			mSaleListitem.setDisplayContent(mSaleListitem.getName() + " " + mSaleListitem.getWeightDesc() + mSaleListitem.getmTareDesc());
			mSaleListitem.setDisplayContent(mSaleListitem.getName() + " " + mSaleListitem.getWeightDesc());
			mTransMgr.mSaleListItems.addItemToList(mSaleListitem);
			return;
		}
		
//		if(posLineItem != null && posLineItem.getUpc().substring(0, 1).equals("5")){
//			mTransMgr.mSaleListItems.AnalysisVdrCoupon(posLineItem.getUpc());
//		}
		UPC upc = new UPC(posLineItem.getUpc(), UPC.INPUT_BY_MANUAL, GlobalInfo.getInstance().isNormalize);
		if(!mRefundMode){
			if (upc.IsVdrCoupon) {
				if(!mRefundMode && mTransMgr.TransType != TransactionType.RETURN){
					mTransMgr.mSaleListItems.addVdrCoupon(upc);
				}
				return;
			}
		}
		
		Product product = mProductService.Find(upc.code);
		if (product == null || !product.getIsActive().equals("A"))
			return;

		mSaleListitem.setItemType(ItemType.REGULAR);
		mSaleListitem.setUpc(upc.code);
		mSaleListitem.setRefund(mRefundMode);
		mSaleListitem.setName(product.getName1());
		mSaleListitem.setDisplayContent(product.getName1());
		mSaleListitem.setDescription(product.getDesc());
		mSaleListitem.setBottleDeposit(product.getBottle_deposit());
		mSaleListitem.setTareCount(ServiceManager.getInstance().mTareSettingService.HaveTare(product.getBarcode()));
		mSaleListitem.setDep(product.getDep());
		mSaleListitem.setFollowdep(product.getFollowdep());
		mSaleListitem.setTax1(product.getTax1());
		mSaleListitem.setTax2(product.getTax2());
		mSaleListitem.setTax3(product.getTax3());
		mSaleListitem.setTax4(product.getTax4());
		mSaleListitem.setTax5(product.getTax5());
		mSaleListitem.setTax6(product.getTax6());
		mSaleListitem.setIsWeight(posLineItem.getWeight() >0?true:false);
		mSaleListitem.setFoodstamp(product.getFoodstamp());
		mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(product.getAgeLinkNo()));
		mSaleListitem.setNodiscount(product.getNodiscount());
		mSaleListitem.setIscoupon(product.getIscoupon());
		if (mSaleListitem.getIscoupon()) {
			mSaleListitem.setItemType(ItemType.COUPON);
		}
		mSaleListitem.setWic(product.isWic());
		mSaleListitem.setCvv(product.isCvv());
		mSaleListitem.setServiceItem(product.isServiceItem());
		mSaleListitem.setPrinter_id(product.getPrinter_id());
		mSaleListitem.setUpc(product.getBarcode());
		mSaleListitem.setUnitPrice(product.getPrice());
		mSaleListitem.setQty(posLineItem.getQty());
		mSaleListitem.setPkgItem(upc.IsPackageItem);
		mSaleListitem.setPrice(product.getPrice() !=Math.abs(posLineprice)?product.getPrice():Math.abs(posLineprice));
		mSaleListitem.setRefund(posLineItem.getType().equals("R") ? true : false);
		mSaleListitem.setIscoupon(posLineItem.getType().equals("Q") ? true : false);
		mSaleListitem.setIsMultCoupon(product.getIs_mult_coupon());
//		String isVdrcoupon = upc.code.substring(0, 1);
		mSaleListitem.setVdr_code(upc.code.substring(2, 7));
		mSaleListitem.setFam_code(upc.code.substring(7, 10));
		mSaleListitem.setVdr_coupon_code_no(upc.code.substring(10, 12));
		String vdrCouponBarcode = CheckVdrCoupon(upc.code);
//		ads;
		if(!vdrCouponBarcode.equals("")){
			String[] VdrCoupon = new String[currentQty];
			for (int i = 0; i < VdrCoupon.length; i++) {
				VdrCoupon[i] = vdrCouponBarcode;
			}
			mSaleListitem.setVdrCouponBarcode(VdrCoupon);
		}

		if (mSaleListitem.getBottleDeposit() > 0) {
			mBottleSetting = ServiceManager.getInstance().mBottleSettingService.Find(mSaleListitem.getBottleDeposit());
			if (mBottleSetting != null) {
				mSaleListitem.setmBottleSeting(mBottleSetting);
			}
		}

		// set tax1 , tax2 ,tax3 ,tax4
		deptSetting = mSubDepartmantService.Find(mSaleListitem.getDep());
		if (deptSetting != null) {

			mSaleListitem.setDep_group(mSubDepartmantService.getGroupNobyid(deptSetting.getSd_id()));
			mSaleListitem.setMdepartment(mSubDepartmantService.getDepNoById(deptSetting.getSd_id()));
		}

		if (mSaleListitem.getFollowdep() && deptSetting != null) {
			mSaleListitem.setTax1(deptSetting.getTax1());
			mSaleListitem.setTax2(deptSetting.getTax2());
			mSaleListitem.setTax3(deptSetting.getTax3());
			mSaleListitem.setTax4(deptSetting.getTax4());
			mSaleListitem.setTax5(deptSetting.getTax5());
			mSaleListitem.setTax6(deptSetting.getTax6());
			mSaleListitem.setIsWeight(deptSetting.getScale_weight());
			mSaleListitem.setFoodstamp(deptSetting.getFood_stamp());
			mSaleListitem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(deptSetting.getAge()));
			mSaleListitem.setNodiscount(deptSetting.getNo_discnt());
			mSaleListitem.setWic(deptSetting.isWic());
			mSaleListitem.setCvv(deptSetting.isCvv());
		}

		mSaleListitem.setPoslineno(posLineItem.getNo());
		mPosLineTaresList = new ArrayList<PosLineTares>();
		mTareSetting = new ArrayList<TareSetting>();
		mPosLineTaresList = ServiceManager.getInstance().mPosLineTaresService.Find(posLineItem.getNo());
		if (mPosLineTaresList != null) {
			for (int i = 0; i < mPosLineTaresList.size(); i++) {
				TareSetting tsetting = new TareSetting();
				tsetting.setQty(mPosLineTaresList.get(i).getLt_qty());
				tsetting.setTa_no(mPosLineTaresList.get(i).getLt_tare_no());
				mTareSetting.add(tsetting);
			}
			mSaleListitem.setmTareSetting(mTareSetting);
			mSaleListitem.setTareCount(mPosLineTaresList.size());
		}

		if (!mSaleListitem.getPkgItem()) {
			if (mSaleListitem.getIsWeight()) {
				mSaleListitem.setWeight(posLineItem.getWeight());
				mSaleListitem.setPrice(posLineItem.getPrice());
				mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit);

				int tmpTareQty = ServiceManager.getInstance().mPosLineTaresService.getManualTare(posLineItem.getNo());
				if (tmpTareQty > 0) {
					mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit);
					mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(tmpTareQty * mGlobalInfo.tareRate, mGlobalInfo.decimalPoint));

				} else {
					double poslinetare = ServiceManager.getInstance().mPosLineTaresService.getTotalTare(posLineItem.getNo()) * GlobalInfo.getInstance().tareRate;
					if (poslinetare > 0) {
						mSaleListitem.setWeightDesc(MoleQUtil.fixWeight(mSaleListitem.getWeight(), mGlobalInfo.decimalPoint) + mGlobalInfo.weightUnit);
						mSaleListitem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(poslinetare, mGlobalInfo.decimalPoint));
					}
				}

			} else {
				mSaleListitem.setWeight(0);
				
			}
		}else{
			mSaleListitem.setPrice(posLineprice);
			mSaleListitem.setWeight(posLineItem.getWeight());
			mSaleListitem.setItemType(ItemType.PACKAGE_ITEM);
		}

		this.ProcessByPriceSetting();

		mTransMgr.mSaleListItems.addItem(mSaleListitem);

		if (mSaleListitem.isRefund()) {
			mTransMgr.refundCount ++;
		}
		List<PosLineDiscnt> mPosLineDiscnt = ServiceManager.getInstance().mPosLineDiscntService.Find(mSaleListitem.getPoslineno());
		if (mPosLineDiscnt != null && mPosLineDiscnt.size() > 0 && !mSaleListitem.getNodiscount()) {
			ItemDiscountSetting mDiscountSetting = null;

			for (int i = 0; i < mPosLineDiscnt.size(); i++) {	
				int discntno = mPosLineDiscnt.get(i).getLd_discnt_no();
			    double discntvalue = mPosLineDiscnt.get(i).getLd_value();
				if (discntno > 0) {
					mDiscountSetting = ServiceManager.getInstance().mDiscountSettingService.Find(discntno);
					if (mDiscountSetting == null)
						continue;
				}else{
					mDiscountSetting = null;
				}
				
				SaleListItem  discntAmtItem =  mTransMgr.mSaleListItems.createItemDiscount(mSaleListitem, mPosLineDiscnt.get(i).getLd_id(), mDiscountSetting,discntno,discntvalue);

				discntAmtItem.setHavepolinediscnt(true);

				mTransMgr.mSaleListItems.addItemToList(discntAmtItem);

			}
		}

		// add item coupon
		List<PosLineCoupon> mPosLineCoupon = ServiceManager.getInstance().mPosLineCouponService.Find(mSaleListitem.getPoslineno());
		if (mPosLineCoupon != null && mPosLineCoupon.size() > 0) {

			PosLineCoupon posLineCoupon = new PosLineCoupon();
			for (int i = 0; i < mPosLineCoupon.size(); i++) {

				posLineCoupon = mPosLineCoupon.get(i);
				if (posLineCoupon == null)
					continue;

				SaleListItem couponAmtItem = mTransMgr.mSaleListItems.createItemCoupon(mSaleListitem, posLineCoupon.getLc_id(), posLineCoupon.getLc_value(), posLineCoupon.getLc_type());

				couponAmtItem.setHavepolinecoupon(true);

				mTransMgr.mSaleListItems.addItemToList(couponAmtItem);

			}
		}

	}

	@Override
	public void onErrorEvent(String res) {
		Toast.makeText(this, "onErrorEvent:'" + res + "'", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onScannerEvent(String res) {
	
		UPC barcode = new UPC(res, UPC.INPUT_BY_SACNNER, GlobalInfo.getInstance().isNormalize);
		
		if (barcode.IsVdrCoupon) {
			if(!mRefundMode && mTransMgr.TransType != TransactionType.RETURN){
				mTransMgr.mSaleListItems.addVdrCoupon(barcode);
			}
		}else{
			this.keySearchItem(barcode);
		}
		
	}

	@Override
	public void onShowItem(SaleListItem item) {

	}

	Handler loadPosLineUpdateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MoleQConstants.SHOW_PROCESSING:
				mDeviceManager.screen.displayLine("Pos Line Item(s)" + "\n" + " Loading");
				DialogManager.show(SaleActivity.this, DialogManager.PROCESSING_POS_LINE);

				break;
			case MoleQConstants.HIDE_PROCESSING:
				mDeviceManager.screen.displayLine("Pos Line Item(s)" + "\n" + " Completed");
				DialogManager.hide(DialogManager.PROCESSING_POS_LINE);

				break;
			case MoleQConstants.REFRESH_SALE_DISPLAY:
				
				DialogManager.hide(DialogManager.PROCESSING_POS_LINE);
				
				Log.i("com.ming", "load item complete.");
				int lastPosition = mTransMgr.mSaleListItems.getItemCount() - 1;
				scrollToRow(lastPosition);

				refreshDisplayContent();

				int verifyAge = mTransMgr.Age;
				if (verifyAge <= 0 && mTransMgr.haveAgeVerifyItem()) {
					mTransMgr.mLoadPendingItemMode = true;
					DialogManager.show(SaleActivity.this, DialogManager.DATE_SELECTION_DIALOG);
					return;
				}

				if (verifyAge > 0 && mTransMgr.haveInvalidAgeItem(verifyAge)) {
					MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_old_enough_2));
					TransactionManager.getInstance().mSaleListItems.removeInvalidAgeItem(verifyAge);
					TransactionManager.getInstance().announceChanges();
					return;
				}
				
				//void invalid wic cvv item
				if (mTransMgr.TransType == TransactionType.WIC) {
					
					if (mTransMgr.haveInvalidWICItem()) {
						MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_wic_item));
						TransactionManager.getInstance().mSaleListItems.removeInvalidWICItem();
						return;
					}
					
					if (mTransMgr.getAmountPayable() > mTransMgr.CVVWicPrice) {
						MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_wic_over_amount));
						TransactionManager.getInstance().mSaleListItems.removeInvalidWICAmountItem();
						return ;
					}
					
					if (mPosLineCvvWic.getVw_end_date() != null && mPosLineCvvWic.getVw_end_date() != "" 
							&& Integer.valueOf(mPosLineCvvWic.getVw_end_date()) < Integer.valueOf(MoleQUtil.getNowwithFormat("yyyyMMdd"))) {
						DialogManager.show(SaleActivity.this, DialogManager.WIC);
						MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_wic_invalid_date));
						
					}
				}
				
				if (mTransMgr.TransType == TransactionType.CVV) {
					if (mTransMgr.haveInvalidCVVItem()) {
						MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_cvv_item));
						TransactionManager.getInstance().mSaleListItems.removeInvalidCVVItem();
						return;
					}
					
					if (mPosLineCvvWic.getVw_end_date() != null && mPosLineCvvWic.getVw_end_date() != ""
							&& Integer.valueOf(mPosLineCvvWic.getVw_end_date()) < Integer.valueOf(MoleQUtil.getNowwithFormat("yyyyMMdd"))) {
						mPosLineCvvWic.isInvalidDate = true;
						DialogManager.show(SaleActivity.this, DialogManager.CVV);
						MessageBox.show(SaleActivity.this, SaleActivity.this.getResources().getString(R.string.msg_not_wic_invalid_date));
						
					}
				}
				/////////
				break;

			case MoleQConstants.DISPLAY_PHOTON:
				Bitmap bm = (Bitmap) msg.obj;
				if (ivProductPic != null) {
					if (bm == null) {
						// ivProductPic.setImageResource(R.drawable.moleqlogo);
						bm = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.moleqlogo);
					}
					ivProductPic.setImageBitmap(bm);
				}
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void onAnnounceCartChanges() {
		if (mTransMgr.mLoadPendingItemMode)
			return;

		Log.i("com.ming.saleactivity", "onAnnounceCartChanges -> itemcount:" + mTransMgr.mSaleListItems.getItemCount());

		if (mTransMgr.mSaleListItems.getItemCount() == 0) {
			showImage(null);
			mTransMgr.setBirthdayDate("");
		}
		refreshDisplayContent();

	}

	@Override
	public void onSelectedIndex(int idx) {
		if (mTransMgr.mLoadPendingItemMode)
			return;

		Log.i("com.ming.saleactivity", "onSelectedIndex ->" + idx);
		this.scrollToRow(idx);
	}

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

			scrollToRow(arg2);

		}
	};

	public void scrollToRow(int row) {
		if (mTransMgr.mLoadPendingItemMode)
			return;
 
		if (row < 0)
			return;

		TransactionManager.getInstance().mSaleListItems.mSelectIndex = row;
		mAdapter.setSelectedRow();

		SaleListItem item = mTransMgr.mSaleListItems.getItem(row);
		Bitmap bm = ServiceManager.getInstance().mPicService.getImageByUPC(item.getUpc());
		showImage(bm);
		// showItemToDisplayScreen(row);

		Log.i("com.ming", ">>>> scrollToRow ->" + row + " ");
		mDeviceManager.screen.displayLine(item.getName() + "\n" + " " + MoleQUtil.fixPriceForScreen(item.getPrice()));

		if (mTransMgr.mSaleListItems.lastRowIsSelected()) {
			mListView.setSelection(mTransMgr.mSaleListItems.mSelectIndex);
		}
	}

	public void refreshDisplayContent() {
		tv_qty.setText(String.valueOf(mNumberPad.getQty()));

		tvSubTotal.setText(MoleQUtil.fixNumber(mTransMgr.getSubTotal()));
		tvTax.setText(MoleQUtil.fixNumber(mTransMgr.getTotalTax()));
		tvTotal.setText(MoleQUtil.fixNumber(mTransMgr.getAmountPayable()));

		if (mTransMgr.getTransDiscount() < 0) {
			tvDiscount_num.setVisibility(View.VISIBLE);
			tvDiscount.setVisibility(View.VISIBLE);
			tvDiscount.setText(mTransMgr.TransDntValue + "% " + String.format(this.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));
			tvDiscount_num.setText(MoleQUtil.fixNumber(mTransMgr.getTransDiscount()));
		} else {
			tvDiscount_num.setVisibility(View.INVISIBLE);
			tvDiscount.setVisibility(View.INVISIBLE);
			tvDiscount_num.setText("");
			mTransMgr.TransDntType = "";
			mTransMgr.TransDntValue = 0;
		}

		if (mRefundMode && mTransMgr.TransType == TransactionType.SALE) {
			tvtrnstype.setVisibility(View.VISIBLE);
			tvtrnstype.setText("Refund Key");
		} else if (mTransMgr.TransType == TransactionType.RETURN) {
			tvtrnstype.setVisibility(View.VISIBLE);
			tvtrnstype.setText("Refund");
		} else {
			tvtrnstype.setVisibility(View.INVISIBLE);
		}
		
		if (mTransMgr.TransType == TransactionType.WIC) {
			tvsptrnstype.setText("WIC "+ GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber( mTransMgr.CVVWicPrice - mTransMgr.getAmountPayable()));
			tvsptrnstype.setVisibility(View.VISIBLE);
		}else if(mTransMgr.TransType == TransactionType.CVV){
			if (mTransMgr.getAmountPayable() > 0) {
				double cvvPrice =mTransMgr.CVVWicPrice - mTransMgr.getAmountPayable();
				if (cvvPrice >= 0) {
					tvsptrnstype.setText("CVV "+ GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(cvvPrice));
				}else{
					tvsptrnstype.setText("CVV ("+ GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(cvvPrice*-1)+")");
				}
			}else{
				tvsptrnstype.setText("CVV "+ GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(mTransMgr.CVVWicPrice));
			}
		
			tvsptrnstype.setVisibility(View.VISIBLE);
		}else{
			tvsptrnstype.setText("");
			tvsptrnstype.setVisibility(View.INVISIBLE);
		}

		if (mTransMgr.manualTare > 0) {
			tv_tare.setVisibility(View.VISIBLE);
			tv_tare_num.setVisibility(View.VISIBLE);
			tv_tare_num.setText(MoleQUtil.fixNumber(mTransMgr.manualTare * GlobalInfo.getInstance().tareRate));
		} else {
			tv_tare.setVisibility(View.INVISIBLE);
			tv_tare_num.setVisibility(View.INVISIBLE);
			tv_tare_num.setText(MoleQUtil.fixNumber(0));

		}

		if (mTransMgr.shiftNum >= 0 || mTransMgr.shiftFs == true) {
			String shifttext = "SHIFT ";
			if (mTransMgr.shiftNum > 0)
				shifttext += "T" + String.valueOf(mTransMgr.shiftNum);
			if (mTransMgr.shiftNum == 0)
				shifttext += "TA";
			if (mTransMgr.shiftFs == true)
				shifttext += "F";
			tv_shift.setVisibility(View.VISIBLE);
			tv_shift.setText(shifttext);
		} else {
			tv_shift.setVisibility(View.INVISIBLE);
			tv_shift.setText("");
		}

	}

	@Override
	public void onNoItemInList() {
		// TODO Auto-generated method stub

	}
}
